Different log files for multiple threads using log4j2

前端 未结 2 1511
梦谈多话
梦谈多话 2021-01-06 14:43

I am running a Java application in which I am invoking multiple threads, each with some unique names. Now I want to create multiple log files for each of them and the name o

2条回答
  •  自闭症患者
    2021-01-06 15:00

    I agree a RoutingAppender is the way to go. I initially used the routing appender in conjunction with the ${ctx:threadName} lookup where the 'ctx' uses the ThreadContext. I found that I would have to sprinkle in the code a line like this:

    ThreadContext.put("threadName", Thread.currentThread().getName());
    

    While that code works it's not extensible in the design of the code. If I were to add a new java.lang.Runnable to the code base, I would have to also include that line.

    Rather, the solution seems to be to implement the 'org.apache.logging.log4j.core.lookup.StrLookup' and register the @Plugin with the PluginManager Like this:

    Class: ThreadLookup

    package my.logging.package    
    import org.apache.logging.log4j.core.LogEvent;
    import org.apache.logging.log4j.core.config.plugins.Plugin;
    import org.apache.logging.log4j.core.lookup.StrLookup;
    
    @Plugin(name = "thread", category = StrLookup.CATEGORY)
    public class ThreadLookup implements StrLookup {
    
    @Override
    public String lookup(String key) {
        return Thread.currentThread().getName();
    }
    
    @Override
    public String lookup(LogEvent event, String key) {
        return event.getThreadName() == null ? Thread.currentThread().getName()
                : event.getThreadName();
    }
    
    }    
    

    Configuration: log4j2.xml (packages attribute of the Configuration registers the @Plugin with the PluginManager)

    
    
        
            
                
                    
                        
                        
                        
                            
                        
                        
                    
                
            
        
        
            
        
    
    
        
            
        
    
    

提交回复
热议问题