简体   繁体   English

Log4j V2自定义布局

[英]Log4j V2 Customizing Layout

I need to filter Log4j output to remove "sensitive" information like passwords from the log messages. 我需要过滤Log4j输出以从日志消息中删除“敏感”信息,例如密码。 The goal is to do something like this: 目标是执行以下操作:

Replace: 更换:

05-Jan-2018 INFO [org.my.application] Username=Bob  Password=myWeakPassword

With: 附:

05-Jan-2018 INFO [org.my.application] Username=Bob  Password=*********

This is fairly easy to do in Log4j V1, by extending the PatternLayout class: 在Log4j V1中,通过扩展PatternLayout类,这很容易做到:

public class CustomPatternLayout extends org.apache.log4j.PatternLayout {
    @Override
    public String format(LoggingEvent event) {
        String temp = super.format(event);
        return doFilteringStuff(temp);
    }
}

However, in Log4j V2 the PatternLayout class was made "final" and the whole architecture was changed. 但是,在Log4j V2中,将PatternLayout类设置为“最终”,并且更改了整个体系结构。 There no longer seems to be a simple way to intercept/override the calls to the PatternLayout object. 似乎不再存在一种简单的方法来拦截/覆盖对PatternLayout对象的调用。 I looked at the Apache documentation but there's not much information. 我查看了Apache文档,但没有太多信息。

I checked this question and this question but neither one has much help to offer. 我检查了这个问题这个问题,但是没有人提供太多帮助。

I realize this is a very "general" question but does anyone know a straightforward way to do this in Log4j V2, or have any advice on this? 我意识到这是一个非常“笼统”的问题,但是没有人知道在Log4j V2中执行此操作的直接方法,或者对此有任何建议吗?

I think what you're looking for is the RewriteAppender . 我认为您正在寻找的是RewriteAppender From the manual: 从手册中:

The RewriteAppender allows the LogEvent to manipulated before it is processed by another Appender. RewriteAppender允许LogEvent在另一个Appender处理之前进行操作。 This can be used to mask sensitive information such as passwords or to inject information into each event. 这可用于掩盖敏感信息(例如密码)或将信息注入每个事件。

Please refer to this answer for a full example of using the RewriteAppender to mask sensitive content. 请参考此答案以获取使用RewriteAppender掩盖敏感内容的完整示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM