Logback:通过过滤器修改消息? [英] Logback: modify message via filter?
问题描述
匹配过滤器后可以修改日志事件吗?
It it possible to modify a log event after matching a filter?
我有一个Web容器(Jersey),它在ERROR级别记录未捕获的异常。但是,对于服务器(Jetty)抛出的某些异常(EofException),我想将它们记录在较低级别(INFO)。
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).
我可以删除那些消息完全使用与异常类型(EofException)匹配的Logback过滤器。但我没有找到一个支持的方法来修改日志事件,例如,更改日志级别。
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.
推荐答案
你可以模拟这种行为使用TurboFilter通过使用提供的记录器记录您自己的修改过的消息,并拒绝原始记录。
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"));
}
}
这篇关于Logback:通过过滤器修改消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!