Configuring two logback appenders independently

2019-09-11 13:37发布

问题:

I might be asking something trivial, but what I've tried doesn't seem to work. With my "MAIN" appender, I want to log all "info"s everywhere, except in a third-party package (let's call it boring), which produces too many of them (so I look at warnings only). Additionally, I want to log "debug"s in my interesting package. This works fine with the following logback.groovy:

root(INFO, ["MAIN"])
logger("interesting", DEBUG, ["MAIN"])
logger("boring", WARN, ["MAIN"])

Now I want to configure a different appender logging one level more like

root(DEBUG, ["DETAIL"])
logger("interesting", TRACE, ["DETAIL"])
logger("boring", INFO, ["DETAIL"])

This also works, but when I put both together, it doesn't. I can imagine that this is caused by the fact that each Logger is either on or off for a given level. I'm aware that for the behavior I want, the loggers in the "boring" package must be on the INFO level (because of the DETAIL appender) and that the messages for the MAIN appender are to be filtered, but I can't see how to configure this.

UPDATE

I see I was doing nearly everything wrong. The line

logger("interesting", DEBUG, ["MAIN"])

says nothing like "set the level to DEBUG for the MAIN appender and the package interesting and below"), it does two independent things instead:

  • set the level to DEBUG for the package interesting and below
  • add the MAIN appender to the "interesting" Logger

回答1:

This seems to be impossible without writing an own filter, which is fortunately pretty easy. I ended up with something like

root(DEBUG, ["DETAIL", "MAIN"])
// settings for the most detailed appender
logger("interesting", TRACE)
logger("boring", INFO)

appender("MAIN", ...) {
    ...
    filter = new MyFilter()
        .deny("boring", INFO)
        .accept("interesting", DEBUG)
        .deny("", DEBUG)
}

where deny and accept are my methods adding entries to MyFilter. The entries are evaluated sequentially, i.e.,

  • in package boring and below, everything with level INFO or below gets denied
  • in package interesting and below, everything with level DEBUG or above gets accepted
  • otherwise, in any package, everything with level DEBUG or above gets denied

Inspired by this question.