我需要过滤 Log4j 输出以从日志消息中删除密码等“敏感”信息。目标是做这样的事情:
替换:
05-Jan-2018 INFO [org.my.application] Username=Bob Password=myWeakPassword
与:
05-Jan-2018 INFO [org.my.application] Username=Bob Password=*********
通过扩展 PatternLayout 类,这在 Log4j V1 中相当容易做到:
public class CustomPatternLayout extends org.apache.log4j.PatternLayout {
@Override
public String format(LoggingEvent event) {
String temp = super.format(event);
return doFilteringStuff(temp);
}
}
但是,在 Log4j V2 中,PatternLayout 类已成为“最终”类,并且整个架构发生了变化。似乎不再有一种简单的方法来拦截/覆盖对 PatternLayout 对象的调用。我看了Apache documentation但没有太多信息。
我检查了this question和 this question但两人都无法提供太多帮助。
我意识到这是一个非常“普遍”的问题,但有人知道在 Log4j V2 中执行此操作的简单方法,或者对此有任何建议吗?
最佳答案
我认为您正在寻找的是 RewriteAppender 。来自手册:
The RewriteAppender allows the LogEvent to manipulated before it is processed by another Appender. This can be used to mask sensitive information such as passwords or to inject information into each event.
请引用this answer有关使用 RewriteAppender 屏蔽敏感内容的完整示例。
关于java - Log4j V2 自定义布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48176731/