Filtering specific exceptions when using log4j

by Jelmer KuperusAugust 23, 2011

A while ago I was working on a project where a background job was being triggered every few seconds or so. This job would call a method on a service, that connected to a remote backend, that was regularly unavailable.

When the backend was down, the logs would be flooded with long stacktraces every few seconds. Making it all but impossible to spot actual errors  amid the carnage.

To solve this problem I could have disabled logging for this service completely. But in this case that seemed like a bad idea. This service was, by all means and purposes a kitchen sink. By disabling logging completely I would run the risk of also swallowing legitimate errors. What I really wanted to do was filter out only this “BackendNotAvailableException”

Fortunately there is a way to do that. Contained within Apache Extras Companion for Apache log4j there is a filter called ExpressionFilter that you can use to do exactly that. Here’s an example of how to configure it for this usecase.

<br>
&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br>
&lt;!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"&gt;<br>
&lt;log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false"&gt;<br>
    &lt;appender name="CONSOLE"&gt;<br>
        &lt;param name="Target" value="System.out"/&gt;<br>
        &lt;layout&gt;<br>
            &lt;param name="ConversionPattern" value="%d %p [%c] - %m%n"/&gt;<br>
        &lt;/layout&gt;<br>
        &lt;filter class="org.apache.log4j.filter.ExpressionFilter"&gt;<br>
            &lt;param name="expression" value="EXCEPTION ~= com.company.BackendNotAvailableException" /&gt;<br>
            &lt;param name="acceptOnMatch" value="false"/&gt;<br>
        &lt;/filter&gt;<br>
    &lt;/appender&gt;<br>
    &lt;root&gt;<br>
        &lt;priority value ="INFO" /&gt;<br>
        &lt;appender-ref ref="CONSOLE"/&gt;<br>
    &lt;/root&gt;<br>
&lt;/log4j:configuration&gt;<br>

There is actually a lot more you can do with this filter and i encourage you to check it out in greater detail