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.

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

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