且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何以编程方式在运行时添加Log4J2 appender?

更新时间:2023-01-10 18:29:03

编辑:用于log4j2的最新版本,请参阅 https://***.com/a/ 33472893/1899566 反而。

for the newest versions of log4j2, see https://***.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 {
  //...
}