How to add Log4J2 appenders at runtime programmatically?

Brian Johnson picture Brian Johnson · Mar 15, 2013 · Viewed 36.6k times · Source

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

Answer

Remko Popma picture Remko Popma · Nov 2, 2015

There have been a number of requests to support better programmatic configuration for Log4j 2. Sorry it took so long. As of Log4j 2.4, API was added to log4j-core to facilitate programmatic configuration.

The new ConfigurationBuilder API allows users to construct component definitions. With this API, there is no need to work directly with actual configuration objects (like LoggerConfig and FileAppender) which require a lot of knowledge on how Log4j works under the hood. Component definitions are added to the ConfigurationBuilder, and once all the definitions have been collected all the actual configuration objects (like Loggers and Appenders) are constructed. It feels a bit like the XML configuration syntax, except that you are writing Java code.

Note that the new ConfigurationBuilder API allows user code to create a new configuration or completely replace the existing configuration. If your use case is different, and you want to programmatically modify (rather than replace) an existing configuration after Log4j was started, then you will need to work with actual configuration objects. In that case, please see the Programmatically Modifying the Current Configuration after Initialization section of the manual.