javalogginglog4jlog4j2

How to add Log4J2 appenders at runtime programmatically?


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

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 {
    //...
}

Solution

  • Edit: 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 {
      //...
    }