如何以编程方式在运行时添加 Log4J2 附加程序? [英] How to add Log4J2 appenders at runtime programmatically?
本文介绍了如何以编程方式在运行时添加 Log4J2 附加程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用 XML 配置中的规范以编程方式添加 Log4J2 附加程序?
Is it possible to add Log4J2 appenders programmatically using the specifications from the XML configuration?
我打算在 log4j2.xml 中定义它,然后像这样根据情况选择 appender(不会编译):
I plan to define it all in the log4j2.xml and then pick appenders situationally like this (won't compile):
if (arg[0].equals("log") ) {
Logger.getLogger("loggerNameFromXMLConfig").addAppender("appenderNameFromXMLConfig");
} else {
//...
}
推荐答案
有关 log4j2 的最新版本,请参阅 https:///stackoverflow.com/a/33472893/1899566 代替.
for the newest versions of log4j2, see https://stackoverflow.com/a/33472893/1899566 instead.
我觉得他们不希望你这样做,但这对我有用:
I get the impression they don't want you doing this, but this works for me:
if (arg[0].equals("log") ) {
org.apache.logging.log4j.Logger logger
= org.apache.logging.log4j.LogManager.getLogger("loggerNameFromXMLConfig");
org.apache.logging.log4j.core.Logger coreLogger
= (org.apache.logging.log4j.core.Logger)logger;
org.apache.logging.log4j.core.LoggerContext context
= (org.apache.logging.log4j.core.LoggerContext)coreLogger.getContext();
org.apache.logging.log4j.core.config.BaseConfiguration configuration
= (org.apache.logging.log4j.core.config.BaseConfiguration)context.getConfiguration();
coreLogger.addAppender(configuration.getAppender("appenderNameFromXMLConfig"));
} else {
//...
}
这篇关于如何以编程方式在运行时添加 Log4J2 附加程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文