Logback logger name with wildcard

前端 未结 2 1761
傲寒
傲寒 2021-02-20 00:04

Is it possible to use a wildcard for the logger name which matches different packages so we don\'t have to specify them all individually? So instead of writing

&         


        
2条回答
  •  日久生厌
    2021-02-20 00:22

    You can do that with Filters in the appender. Basically you have to set up a logger for com.* with DEBUG level, and apply a filter which DENIES all DEBUG (or lower) events which are NOT com.*.web.

    I admit that it is quite convoluted.

    Performance-wise it is also poor: DEBUG events are created for all com.* events, and only at the appender they are thrown away or kept.

    Anyway, example logback.xml file:

    
        
            
                
                    
                        !(e.loggerName ==~ "com\\..*\\.web") &&
                        DEBUG.toInt() >= e.level.toInt()
                    
                
                NEUTRAL
                DENY
            
            
                %p [%d{HH:mm:ss,SSS}] %c - %m\n
            
        
    
        
    
        
            
        
    
    

    Test code:

    public void test() throws Exception{
        getLogger("com.package1.web").debug("some debug onto com.package1.web");
        getLogger("com.package2.web").debug("some debug onto com.package2.web");
        getLogger("com.package3.web").debug("some debug onto com.package3.web");
        getLogger("com.package1.web").info("some info onto com.package1.web");
        getLogger("com.package2.web").info("some info onto com.package2.web");
        getLogger("com.package3.web").info("some info onto com.package3.web");
        getLogger("com.package3.notweb").debug("some debug onto com.package3.notweb");
        getLogger("com.package3.notweb").info("some info onto com.package3.notweb");
    }
    
    public Logger getLogger(String loggerName) {
        return LoggerFactory.getLogger(loggerName);
    }
    

    Result:

    DEBUG [12:30:46] com.package1.web - some debug onto com.package1.web
    DEBUG [12:30:46] com.package2.web - some debug onto com.package2.web
    DEBUG [12:30:46] com.package3.web - some debug onto com.package3.web
    INFO [12:30:46] com.package1.web - some info onto com.package1.web
    INFO [12:30:46] com.package2.web - some info onto com.package2.web
    INFO [12:30:46] com.package3.web - some info onto com.package3.web
    INFO [12:30:46] com.package3.notweb - some info onto com.package3.notweb
    

    as you can see, DEBUG logs are written only for com.*.web.

提交回复
热议问题