自定义记录器消息格式Java LoggerFactory.getLogger(getClass())

时间:2014-09-16 09:34:39

标签: java logging handler logback appender

我需要更改标准日志行为,只需用空格替换\ n符号。 在某种程度上可以全局处理记录器的最终消息吗?

作为一个解决方案,我做了自定义Appender,但我不喜欢这种方法中的类型转换。

public class NonPrettyFileAppender extends ConsoleAppender<ILoggingEvent> {
@Override
protected void writeOut(ILoggingEvent event) throws IOException {
    final String origMsg = event.getMessage();
    final String newMsg = origMsg.replace("\n", " ");
    ((LoggingEvent) event).setMessage(newMsg);
    super.writeOut(event);
}

}

1 个答案:

答案 0 :(得分:0)

为处理事件消息创建新的PatternLayout似乎更合适。 它可以用于控制台和文件缓存器

public class NonPrettyPatternEncoder extends PatternLayoutEncoderBase<ILoggingEvent> {

@Override
public void start() {
    PatternLayout patternLayout = new NonPrettyPatternLayout();
    patternLayout.setContext(context);
    patternLayout.setPattern(getPattern());
    patternLayout.setOutputPatternAsHeader(outputPatternAsHeader);
    patternLayout.start();
    this.layout = patternLayout;
    super.start();
}

public static class NonPrettyPatternLayout extends PatternLayout {
    @Override
    protected String writeLoopOnConverters(ILoggingEvent event) {
        if (event.getLevel() == Level.ERROR) {
            return super.writeLoopOnConverters(event);
        } else {
            return super.writeLoopOnConverters(event).replace("\n", " ") + "\n";
        }
    }
}

}