It it possible to modify a log event after matching a filter?
I've got an web container (Jersey) that logs uncaught exceptions at the ERROR level. But, for certain exceptions (EofException) throw by the server (Jetty), I'd like to log them at a lower level (INFO).
I can drop those messages entirely using a Logback filter that matches on the exception type (EofException). But I haven't found a supported method to modify the log event, e.g., change the log level.
In logback-classic, filters can be added to Appender instances. By adding one or more filters to an appender, you can filter events by arbitrary criteria, such as the contents of the log message, the contents of the MDC, the time of day or any other part of the logging event.
Appenders place log messages in their final destinations. A Logger can have more than one Appender. We generally think of Appenders as being attached to text files, but Logback is much more potent than that. Layout prepares messages for outputting.
GitHub - qos-ch/logback: The reliable, generic, fast and flexible logging framework for Java.
Logback uses the same concepts as Log4j. So it's no surprise that even if they are using different file formats, their configurations are very similar. The following code snippet shows the same configuration as I used with Log4j.
You can simulate this behaviour using a TurboFilter by logging your own modified message with the provided logger, and denying the original.
I'm not convinced this sort of hack is a good idea, though.
package com.example.logback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.turbo.TurboFilter;
import ch.qos.logback.core.spi.FilterReply;
public class LogbackTest
{
private static class ModifyingFilter
extends TurboFilter
{
@Override
public FilterReply decide(
Marker marker,
ch.qos.logback.classic.Logger logger,
Level level,
String format,
Object[] params,
Throwable t)
{
if (level == Level.ERROR &&
logger.getName().equals("com.example.logback.LogbackTest") &&
format.equals("Connection successful: {}"))
{
logger.debug(marker, format, params);
return FilterReply.DENY;
}
return FilterReply.NEUTRAL;
}
}
public static void main(String[] args)
{
LoggerContext lc = (LoggerContext)LoggerFactory.getILoggerFactory();
lc.addTurboFilter(new ModifyingFilter());
Logger logger = LoggerFactory.getLogger(LogbackTest.class);
logger.error("Connection successful: {}", "no problem", new RuntimeException("Hi"));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With