Trifork Blog

Axon Framework, DDD, Microservices

Filtering specific exceptions when using log4j

August 23rd, 2011 by
|

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

3 Responses

  1. September 13, 2011 at 11:32 by Jettro Coenradie

    Nice one, will have a good look at it.

  2. November 12, 2012 at 05:06 by Abhishek Kumar

    Good one. It is very useful for eating some common logs that always increases the log file size for no reason.

  3. June 1, 2015 at 20:55 by FiruzzZ

    I am getting this:
    log4j:ERROR Could not instantiate class [org.apache.log4j.filter.ExpressionFilter].
    java.lang.ClassNotFoundException: org.apache.log4j.filter.ExpressionFilter

    And for a good reason, I can’t find it in the lib 1.2.16. Javadocs makes references but there is no such class