Display thread id instead thread name in log

后端 未结 10 767
南笙
南笙 2020-12-31 00:34

I have a Struts application with log4j to display information about application.

The pattern to format log\'s output is as follows:

log4j.appender.RA         


        
10条回答
  •  时光取名叫无心
    2020-12-31 01:14

    Extend PatternLayout as below, and then specify MyPatternLayout with $X{threadId} in the format string.

    This implementation uses ThreadLocal to minimize the performance impact of calculating the Thread ID:

        MyPatternLayout extends PatternLayout {
    
            private final ThreadLocal threadId = new ThreadLocal() {
    
                @Override
                protected String initialValue() {
                    String t = Long.toString(Thread.currentThread().getId());
                    MDC.put("threadId", t);
                    return t;
                }
            };
    
            @Override
            public String format(LoggingEvent event) {
    
                this.threadId.get();
                return super.format(event);
            }
        }
    

提交回复
热议问题