我正在使用 log4j2(版本 - 2.5),我正在尝试编写一个消息转换器插件,它将屏蔽日志消息的一些已知模式。
@Plugin(name = "CustomeMasking",
category = "Converter")
@ConverterKeys({"m"})
public class MyCustomFilteringLayout extends LogEventPatternConverter {
}
当我使用这个插件运行我的 web 应用程序时,我看到了这个警告消息
WARN Converter key 'm' is already mapped to 'class org.apache.logging.log4j.core.pattern.MessagePatternConverter'. Sorry, Dave, I can't let you do that! Ignoring plugin [class MyCustomFilteringLayout].
在探索 log4j2 站点后,我找到了这些引用资料。
If multiple Converters specify the same ConverterKeys, then the load order above determines which one will be used. For example, to override the %date converter which is provided by the built-in DatePatternConverter class, you would need to place your plugin in a JAR file in the CLASSPATH ahead of log4j-core.jar. This is not recommended; pattern ConverterKeys collisions will cause a warning to be emitted. Try to use unique ConverterKeys for your custom pattern converters.
我需要帮助来了解如何为 m/msg 编写自定义转换器。有没有更好的方法呢?
其他详细信息: 我为 MyCustomFilteringLayout 创建了阴影 jar。我这样做的原因是我想将屏蔽逻辑与应用程序分开。
已更新
我已经为自己的 key 创建了转换器,如下所示,
@Plugin(name = "CustomeMasking",
category = "Converter")
@ConverterKeys({"cm"})
public class MyCustomFilteringLayout extends LogEventPatternConverter {
}
这里我不能为相同的 ConverterKeys 编写另一个转换器 - cm? 现在我的 log4j2.xml 具有这种模式布局,
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %cm %ex%n</Pattern>
</PatternLayout>
最佳答案
您的更新解决了问题并回答了如何用自定义消息转换器替换内置消息转换器的问题。它需要一个唯一的 key 。
听起来您想参数化您的模式。许多模式采用 options
参数。您可以使用它来控制行为,因此在您的布局模式中指定 %cm{key1} 将产生与 %cm{key2} 不同的结果。
有关带参数的转换器示例,请参阅 MdcPatternConverter 的源代码.
关于java - 如何屏蔽 log4j2 日志消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36928882/