如何使用log4j2为我的属性文件编写以下内容?
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.null=org.apache.log4j.varia.NullAppender
答案 0 :(得分:1)
您可以将NullAppender实现为插件。
插件实现是这样的:
package myPlugins;
@Plugin(name = "NullAppenderDemo", category = "Core", elementType = "appender", printObject = true)
public classNullAppenderDemo extends AbstractAppender {
private static final long serialVersionUID = 1L;
protected NullAppenderDemo(String name, Filter filter, Layout<? extends Serializable> layout, boolean ignoreExceptions) {
super(name, filter, layout, ignoreExceptions);
}
@Override
public void append(LogEvent event) {
// Nothing is done here !!!
}
@PluginFactory
public static NullAppender createAppender(
@PluginAttribute("name") String name,
@PluginAttribute("ignoreExceptions") boolean ignoreExceptions,
@PluginElement("Layout") Layout<? extends Serializable> layout,
@PluginElement("Filters") Filter filter) {
if (name == null) {
LOGGER.error("No name provided for NullAppender");
return null;
}
return new NullAppenderDemo(name, filter, layout, ignoreExceptions);
}
}
在log4j2配置中指定插件类的包:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration packages="myPlugins">
使用appenders(我更喜欢xml格式的属性,但如果您喜欢这些属性,则可以根据manual进行映射:
<Appenders>
<NullAppender name="null">
</NullAppender>
<Console name="console">
<PatternLayout>
<pattern>
%d %level{length=2} (%c{1.}.%M:%L) - %m%n
</pattern>
</PatternLayout>
</Console>
</Appenders>
<Loggers>
<root level="info">
<appenderRef ref="console" />
</root>
<logger name="nullAppenderPackage" additivity="false">
<appenderRef ref="null" />
</logger>
</Loggers>
但实际上,你可以使用level =&#34; off&#34;没有NullAppender:
<logger name="nullAppenderPackage" level="off">
</logger>
您可以找到更多详情here。
答案 1 :(得分:0)
好奇,但是当你可以配置任何appender过滤掉所有内容时,NullAppender的需求是什么?