Filtering specific exceptions when using log4j
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> <?xml version="1.0" encoding="UTF-8"?><br> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"><br> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false"><br> <appender name="CONSOLE"><br> <param name="Target" value="System.out"/><br> <layout><br> <param name="ConversionPattern" value="%d %p [%c] - %m%n"/><br> </layout><br> <filter class="org.apache.log4j.filter.ExpressionFilter"><br> <param name="expression" value="EXCEPTION ~= com.company.BackendNotAvailableException" /><br> <param name="acceptOnMatch" value="false"/><br> </filter><br> </appender><br> <root><br> <priority value ="INFO" /><br> <appender-ref ref="CONSOLE"/><br> </root><br> </log4j:configuration><br>
There is actually a lot more you can do with this filter and i encourage you to check it out in greater detail