Display thread id instead thread name in log

后端 未结 10 763
南笙
南笙 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:15

    Another elegant solution with log4j2 is to use org.apache.logging.log4j.core.pattern.LogEventPatternConverter.

    You can write a class like this

    @Plugin(name = "ThreadIdConverter", category = "Converter")
    @ConverterKeys({ "tid" })
    public class ThreadIdConverter extends LogEventPatternConverter {
    
        protected ThreadIdConverter(String name, String style) {
            super(name, style);
        }
    
        @Override
        public void format(LogEvent event, StringBuilder toAppendTo) {
            toAppendTo.append(getThreadId());
        }
    
        protected String getThreadId() {
            long id = Thread.currentThread().getId();
            return Long.toHexString(id);
        }
    
        public static ThreadIdConverter newInstance(String[] options) {
            return new ThreadIdConverter("tid", "tid");
        }
    }
    

    In this way you are creating a new pattern tid and you can use it when you define your appender's layout

    
        
            
                %d{dd-MMM HH:mm:ss.SSS} %-7level [%5tid] %logger - %message%n
            
        
    
    

    The last important thing to remember is how to activate your log4j2 plugin. To do it you have to add the package that contains your plugins in the log4j2 configuration file using the package attribute on Configuration node

    
    
    
        
            
                
                    %d{dd-MMM HH:mm:ss.SSS} %-7level [%5tid] %logger - %message%n
                
            
        
        
            
                
            
            
        
    
    

提交回复
热议问题