java - 如何屏蔽 log4j2 日志消息

标签 java logging log4j log4j2

我正在使用 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 站点后,我找到了这些引用资料。

Reference

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/

相关文章:

java - 投影矩阵 OpenGL/GLSL 问题

java - 如何在 Eclipse 中的项目类路径中添加 log4j.properties 文件的路径?

java - 使用 list 的类路径顺序

java - 如何从浏览器启动 Word 文档作为模板?

java - 如何在 eclipse java 应用程序中添加 java 参数以及类路径?

tomcat - Hudson 日志进入 stderr 并且也没有滚动

bash - 如何使用 bash 记录 dmidecode 结果

java - 记录语法详细信息

scala - 如何禁用 java ortools CP 求解器日志记录?