Ask Your Question
3

What is the solution to prevent a specific type of Exception from being logged in Logback?

asked 2022-05-29 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-10-02 16:00:00 +0000

lakamha gravatar image

One solution is to use Logback's filtering capabilities to exclude the specific type of Exception from being logged. This can be done by creating a custom filter that checks the type of the Exception and returns a decision to either include or exclude it from the log. The filter can then be added to the Logger or Appender configuration to ensure that the excluded Exception is not logged.

Here is an example of how to create the custom filter:

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.AbstractMatcherFilter;

public class CustomExceptionFilter extends AbstractMatcherFilter<ILoggingEvent> {

    @Override
    public FilterReply decide(ILoggingEvent event) {
        if (event.getThrowableProxy() != null && event.getThrowableProxy().getClassName()
                .equals("com.example.ExcludedException")) {
            return FilterReply.DENY; // exclude the Exception from log
        }
        return FilterReply.ACCEPT; // include all other events in log
    }
}

In this example, the filter checks if the event has a ThrowableProxy (i.e., an Exception) and if its class name is "com.example.ExcludedException". If it is, the filter returns FilterReply.DENY to exclude the event from the log. If not, it returns FilterReply.ACCEPT to include the event in the log.

To use this filter in Logback configuration, add the following to the <appender> or <logger> section:

<filter class="com.example.CustomExceptionFilter" />

This will apply the custom filter to the Appender or Logger and exclude the specified Exception from being logged.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-05-29 11:00:00 +0000

Seen: 10 times

Last updated: Oct 02 '22