How to customize the dynamic properties in logback.xml

Original Address: http://blog.jboost.cn/trick-logback-prop.html

When logging logback to Web applications, we have to specify the log file output formats and output path by configuring the appender in logback.xml, which deployed on a host or a single instance of the file system is no problem, but if the deployment of more than instances (for example, by way of the vessel), multiple instances of the same file at the same time to write the log might cause problems. Log file for each time instance can be distinguished, such as IP, or the UUID, or a combination of both forms. In fact, this issue involves how to customize the dynamic properties of the logback.xml in.

There are four possible ways to achieve logback.xml acquire custom variable values:

  1. Mode by setting environment variables or delivery system properties (such as by passing at program startup -D), both of which can be directly through the logback.xml  ${变量名} acquired.
  2. Since the timing of the loading logback.xml defined before loading would need to be set which is injected into the context logback in this way is relatively complex, not discussed herein.
  3. Attribute value provided by the interface realized PropertyDefiner
  4. To set a property value by implementing the interface LoggerContextListener

The first way is simple, but can not be generated by a program attribute value, a second slightly more complex embodiment, two methods describes herein after.

PropertyDefiner way

First, define a class that implements PropertyDefiner interface, it can be more convenient through inheritance PropertyDefinerBase

Import ch.qos.logback.core.PropertyDefinerBase;
 Import org.slf4j.Logger;
 Import org.slf4j.LoggerFactory; 

Import the java.net.InetAddress;
 Import a java.net.UnknownHostException;
 Import java.util.UUID;
 / ** * 
 * the local IP spliced to the log file name, to distinguish different instances, to avoid conflicts when the cover is stored in the same location 
 * @author ronwxy 
 * @date 2019/8/20 16:17    
 * / 
public  class IPLogDefiner the extends PropertyDefinerBase { 

    Private  static  Final Logger LoggerFactory.getLogger the LOG = (IPLogDefiner. class ); 

    Private  String getUniqName () {
        String LocalIP= null;
        try {
            localIp = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            LOG.error("fail to get ip...", e);
        }
        String uniqName = UUID.randomUUID().toString().replace("-", "");
        if (localIp != null) {
            uniqName = localIp + "-" + uniqName;
        }
        return uniqName;
    }


    @Override
    public String getPropertyValue() {
        return getUniqName();
    }
}

 

Then logback.xml added  <define> configuration attribute specifies the name (in this case, and localIP) and access implemented class attribute value, so that the configuration can  ${localIP}reference the value of the attribute. In the implementation method  getPropertyValue returns the value you need to generate in this case is the return  本地IP-UUID form.

<configuration>
    <define name="localIP" class="cn.jboost.common.IPLogDefiner"/>
    <appender name="interfaceLogFile"
              class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoding>UTF-8</encoding>
        <File>D:\\logs\\elk\\interface-${localIP}.log</File>
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
# 省略了其它配置

 

LoggerContextListener way 

LoggerContextListener define a class that implements the interface, in start method will need to be set is set to the Context logback,

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.LoggerContextListener;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.spi.ContextAwareBase;
import ch.qos.logback.core.spi.LifeCycle;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.UUID;

/***
 * 第二种实现方式
 * @Author ronwxy
 * @Date 2019/8/20 18:45   
 */
public class LoggerStartupListener extends ContextAwareBase 
    implements LoggerContextListener, LifeCycle {

    private boolean started = false;

    @Override
    public void start() {
        if (started) {
            return;
        }
        Context context = getContext();
        context.putProperty("localIP", getUniqName());
        started = true;
    }

    private String getUniqName() {
        String localIp = null;
        try {
            localIp = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            //LOG.error("fail to get ip...", e);
        }
        String uniqName = UUID.randomUUID().toString().replace("-", "");
        if (localIp != null) {
            uniqName = localIp + "-" + uniqName;
        }
        return uniqName;
    }
//省略了其它函数

 

 Logback.xml Then, the configuration as described above listener class can thus  ${localIP} obtain the above  context.putProperty("localIP", getUniqName()); value set up.

<configuration>

    <!--<define name="localIP" class="com.cnbot.common.IPLogDefiner"/>-->
    <contextListener class="cn.jboost.common.LoggerStartupListener"/>
    <define name="localIP" class="com.cnbot.common.IPLogDefiner"/>
    <appender name="interfaceLogFile"class="ch.qos.logback.core.rolling.RollingFileAppender">
        <encoding>UTF-8</encoding>
        <File>D:\\logs\\elk\\interface-${localIP}.log</File>
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
# other configurations are omitted
        </ filter>
            <Level> the INFO </ Level>
              

 

This embodiment can set an arbitrary number of property values, flexible than the former method.

to sum up

Acquiring logback.xml custom attribute value, the attribute value is primarily required before loading the corresponding set, in order to obtain effective when such loading. Although this article is a custom log file name, but not limited to, all variables need to be dynamically acquired can be achieved in this way.



If you feel that there is help, please help forwarding is recommended. I welcome attention to the micro-channel public number: jboost-ksxy
--------------------------------------- ------------------------
Micro-channel public number

Guess you like

Origin www.cnblogs.com/spec-dog/p/11386668.html