本文介绍了如何以编程方式在运行时添加Log4J2 appender?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能Log4J2追加程序编程方式使用XML配置规格补充的吗?

Is it possible to add Log4J2 appenders programmatically using the specifications from the XML configuration?

我打算把它定义都在log4j2.xml,然后从中挑选追加程序situationally像这样(不会编译):

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的最新版本,请参阅反而。

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 appender?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 04:28