Is it possible to suppress only Warn messages in Log4j2 while allowing all others

前端 未结 2 1156
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-22 08:22

I am using log4j2 to log messages in console and in a file. I am getting a lot of Warn message which I do not want. I only want to see Debug and other messages. is it possib

2条回答
  •  温柔的废话
    2020-12-22 08:34

    You can use the LevelRangeFilter to reject the log events.

    Here's a simple class that generates some logs:

    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    
    public class SomeClass {
    
        private static final Logger log = LogManager.getLogger();   
    
        public static void main(String[] args){
    
            if(log.isDebugEnabled())
                log.debug("This is some debug!");
            log.info("Here's some info!");
            log.warn("Warning will be rejected.");
            log.error("Some error happened!");
        }
    }
    

    Here's a basic configuration that just sends all events to console:

    
    
        
            
                
            
        
    
        
            
                
            
        
    
    

    The output generated by the above is:

    21:08:42.215 [main] DEBUG example.SomeClass - This is some debug!
    21:08:42.217 [main] INFO  example.SomeClass - Here's some info!
    21:08:42.217 [main] WARN  example.SomeClass - Warning will be rejected.
    21:08:42.217 [main] ERROR example.SomeClass - Some error happened!
    

    Now we add the LevelRangeFilter to the Console appender:

        
            
            
        
    

    Now the output is:

    21:15:26.987 [main] DEBUG example.SomeClass - This is some debug!
    21:15:26.989 [main] INFO  example.SomeClass - Here's some info!
    21:15:26.989 [main] ERROR example.SomeClass - Some error happened!
    

    As you can see the WARN message is not logged to console.

提交回复
热议问题