在项目的开发过程中,对于log打印时,一次request到response的请求,以及到响应到客户端的数据的请求,我们希望都能够串起来,因此,需要有一个唯一id来标识,这里我们通过log4j2中的logId来实现。 Log4j2中包含一个类:ThreadContext(实际上是一个本地线程) 可以自己生成一个唯一id:比如:uuid logId = uuid;

ThreadContext.put("logId", UUID.randomUUID().toString());

然后在过滤器或者拦截器之前设置:ThreadContext.put("logId", logId); log4j2.xml中配置如下:

<PatternLayout pattern="[LOGID:%X{logId}] %d{yyyy/MM/dd HH:mm:ss.SSS} [%p] %c{1} (%F:%L) %msg%n" />

java代码

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.