How to log multiple threads in different log files?

前端 未结 6 661
南旧
南旧 2020-12-05 12:40

I have a JAVA class that starts various threads that have unique IDs. Each thread should log into a unique log file, named after the ID.log.

Because I only get the u

6条回答
  •  醉梦人生
    2020-12-05 13:15

    For log4j v2 you can use RoutingAppender to dynamically route messages. You can put value for key 'threadId' into the ThreadContext map and then use this id as a part of the file name. There is an example which I have easily applied for the same purpose as yours. See http://logging.apache.org/log4j/2.x/faq.html#separate_log_files

    Be aware when putting values into ThreadContext map: "A child thread automatically inherits a copy of the mapped diagnostic context of its parent." So if you have put a value for key 'threadId' into the parent thread and eventually created multiple threads from it, then all child threads will inherit the value of 'threadId' value. I was not able to simply override this value by using put() one more time - you need to use ThreadContext.clear() or explicitly remove() the value from thread context map.

    Here is my working log4j.xml:

    
    
        
            %d{HH:mm:ss} %-5level - %msg%n
            test logs
        
        
                        
                
             
    
            
                                     
                            
                                
                                        
                                        
                                    
                                 
                        
                            
                        
                  
        
    
                       
            
                
                
                                 
          
    
    

提交回复
热议问题