Logback logger name with wildcard

前端 未结 2 1772
傲寒
傲寒 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:12

    TL;DR

    Logback does not support wildcards at intermediate levels in the logger name.

    Detail

    Logback (implicitly) supports wildcards at the end of the logger name, so effectively means:

    • Classes in com.package1.web and in any sub packages of com.package1.web

    Logback does this by creating a hierarchy of loggers; the logger for com.package1.web is parented by a logger for com.package1 which is parented by a logger for com which is parent by the ROOT logger.

    So, if you declare and then attempt to emit a debug log message for a logger on com.package1.web.foo.bar Logback will walk up that logger's hierarchy until it finds a logger for which the DEBUG level is enabled, it will find this at com.package1.web and hence it will emit the DEBUG log event.

    However, Logback will not create a hierarchy based on a wilcard at an intermediate level in the logger name. So, this ...

    
    

    ... will not cause Logback to create loggers for:

    • com.package1.web
    • com.package2.web
    • com.package3.web

    Logback's hierarchy behaviour will not be applied when the wildcard is presented at an intermediate level in the logger name.

    Possible Solution

    One benefit of this hierarchy behaviour is that it allows you to apply logger configuration to a package and all classes below that package i.e. it creates an association between logger instances based on their parentage. You could make this association by providing an explicit logger name, rather than defaulting it to the current class name.

    For example:

    
    

    Then everywhere you want to use the debug logger just create a Logger instance like so:

    private final Logger logger = LoggerFactory.getLogger("DEBUG_LOGGER");
    

    Clearly, there are drawback to this approach too, I'm just mentioning it here to show that there is another way (other than fully qualified class name) to associate logger instances and apply a level to them.

提交回复
热议问题