log4j2 常见配置并支持logId

声明:原创文章,转载请注明出处。http://www.jianshu.com/u/e02df63eaa87

1、常见配置及解释






    
    
        
        
            
            
        

        
        
            
        

        
            
            
            
            
                
                
            
        

        
            
            
            
            
            
            
                
                
            
        

    

    
    
        
        
        
        
            
            
            
            
        
    

2、Java端配置

运行时指定上述log4j2.xml的配置:

-Dlog4j.configurationFile=./conf/log4j2.xml

3、输出logId或者与log交互

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;

/**
 * Created by think on 2017/1/22 0022.
 */
public class LogTest {
    private static final Logger logger = LogManager.getLogger(LogTest.class);

    static class test extends Thread {
        @Override
        public void run() {
            long time = System.currentTimeMillis();
            ThreadContext.put("logid", String.valueOf( time));
            logger.info("test thread.");
            ThreadContext.clearAll();
        }
    }

    public static void main(String[] args) {
        long time = System.currentTimeMillis() ;
        ThreadContext.put("logid", String.valueOf(time));
        try {
            logger.trace("trace...");
            logger.debug("debug...");
            logger.info("info...");
            logger.warn("warn...");
            logger.error("error...");
            logger.fatal("fatal...");

            test test1 = new test();
            test test2 = new test();
            test1.start();
            test2.start();

        } catch (Exception e) {
            e.printStackTrace();
        }

        ThreadContext.clearAll();
    }
}

输出:

[ TRACE ] [2017-02-04 17:10:27] [ LOGID:199427158 ] [logtest.LogTest.main(LogTest.java:37)] trace...
[ DEBUG ] [2017-02-04 17:10:27] [ LOGID:199427158 ] [logtest.LogTest.main(LogTest.java:38)] debug...
[ INFO ] [2017-02-04 17:10:27] [ LOGID:199427158 ] [logtest.LogTest.main(LogTest.java:39)] info...
[ WARN ] [2017-02-04 17:10:27] [ LOGID:199427158 ] [logtest.LogTest.main(LogTest.java:40)] warn...
[ ERROR ] [2017-02-04 17:10:27] [ LOGID:199427158 ] [logtest.LogTest.main(LogTest.java:41)] error...
[ FATAL ] [2017-02-04 17:10:27] [ LOGID:199427158 ] [logtest.LogTest.main(LogTest.java:42)] fatal...
[ INFO ] [2017-02-04 17:11:38] [ LOGID:199498552 ] [logtest.LogTest$test.run(LogTest.java:20)] test thread.
[ INFO ] [2017-02-04 17:11:38] [ LOGID:199498551 ] [logtest.LogTest$test.run(LogTest.java:20)] test thread.

本文代码可参考:https://github.com/hawkingfoo/log-test

你可能感兴趣的:(log4j2 常见配置并支持logId)