Logback filters

Filtering could be a complicated matter, the official Logback documentation would give you a detailed introduction to the subject, but I guess it can be useful having a more limited view on a few basic features.

We can specify the lower level accepted to log in a logger element (including the root element) setting its level attribute. For instance, if we want to log everything from trace up we specify "trace" as level for the root element:
<root level="trace">
A threshold filter could be used to skip from logging any message with a severity higher than the specified level. In this example a console appender is filtered to show only up to info messages:
<appender name="CApp" class="ch.qos.logback.core.ConsoleAppender">
    <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> 
We can filter so that only messages with a specified severity are logged. This filter accepts only warning messages and discard all the others:
<filter class="ch.qos.logback.classic.filter.LevelFilter">
For more complex filtering we can create a custom filter and refer to it in our configuration file.

If we want to log only INFO, but just the ones among them containing the "hello" text in it, we could define a MyFilter class like this:
package test;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.Filter;
import ch.qos.logback.core.spi.FilterReply;

public class MyFilter extends Filter<ILoggingEvent> {
    public FilterReply decide(ILoggingEvent event) {
        if(event.getLevel() != Level.INFO)
            return FilterReply.DENY;

        if (event.getMessage().contains("hello"))
            return FilterReply.NEUTRAL;
        return FilterReply.DENY;
In our configuration file we refer to it:
<filter class="test.MyFilter">
This approach keeps the XML configuration file simple, delegating the filtering logic to a custom Java class. On the other side, the configuration file gets a bit more obscure - at first sight it is not clear what the filtering is actually doing.

When the filtering rule is very simple, it won't probably make much sense using this approach, maybe a couple of filters in the XML configuration would be a better solution.

No comments:

Post a Comment