log4j and logback custom file storage directory method

       In order to facilitate the management of logs, we created a shared directory between the clusters through network mounting, that is, this disk directory can be accessed on all servers. Therefore, we need to dynamically set the log storage path according to the cluster environment when writing logs.

       Our engineering logs are recorded in two ways: log4j and sl4f+logback

First, log4j custom path

       1. Create a class LogbackCustomName to inherit ServletContextListener.

   public static final String log4jdirkey = "log4jdir";

 @Override
 public void contextDestroyed(ServletContextEvent log4jdirkey) {

  System.getProperties().remove(log4jdirkey);

 }

 @Override
 public void contextInitialized(ServletContextEvent servletcontextevent) {
  InetAddress netAddress = getInetAddress();

//Get the host name This method can also get the host IP but it can only be used in windows

  String log4jdir = getHostName(netAddress);

  System.setProperty(log4jdirkey, log4jdir);
 }

 public static InetAddress getInetAddress() {

  try {
   return InetAddress.getLocalHost();
  } catch (UnknownHostException e) {
   e.printStackTrace();
  }
  return null;

 }

 public static String getHostName(InetAddress netAddress) {
  if (null == netAddress) {
   return null;
  }
  String ip = netAddress.getHostName();
  return ip;
 }
2、修改web.xml文件

       Add monitoring in web.xml

 <listener>
  <listener-class>XXX.XXXX.LogbackCustomName</listener-class>
 </listener>

      This section must be placed before Spring's monitoring, otherwise it will not take effect.

 After the configuration is complete, add ${log4jdir} to the log writing path.

 Second, logback custom path

1. First create the class LogbackCustomName to inherit the PropertyDefinerBase in logback

  @Override
 public String getPropertyValue() {
  String info;
  InetAddress netAddress = getInetAddress();

//Get the host name linux multi-network card cannot specify the specific network card according to the environment, this method can only be used under windows
  info = getHostName(netAddress); 
  return info;

 }

 public static InetAddress getInetAddress() {

  try {
   return InetAddress.getLocalHost();
  } catch (UnknownHostException e) {
   e.printStackTrace();
  }
  return null;

 }

 public static String getHostName(InetAddress netAddress) {
  if (null == netAddress) {
   return null;
  }
  String ip = netAddress.getHostName();
  return ip;
 }

2. Modify the logback.xml configuration file and add custom variables

 <define  name="HostName" class="XXX.XXX..LogbackCustomName" /> 

Then add ${HostName} to the path name when defining the path.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326271917&siteId=291194637