Farath Shba
Farath Shba

Reputation: 31

LOG4J1.x to LOG4J2

I would like to check on the following piece of code where I am stuck at from migrating from LOG4J1.X to LOG4J2.

File f = new File(fullFilePath);
Enumeration apps = logger.getAllAppenders();
if(!f.exists() || !apps.hasMoreElements())
{
logger.removeAllAppenders();
appender = new FileAppender();
appender.setName(fileName);
logger.addAppender(appender);
logger.setLevel(Level.toLevel(level));
}

I could convert the rest of the code successfully to log4j2, however the removeAllAppenders, getAllAppenders, addAppender, setLevel functions are not available under log4j2. Hence, how do I go about replacing them?

Upvotes: 1

Views: 1581

Answers (1)

rgoers
rgoers

Reputation: 9141

In Log4j2 Loggers don't have Appenders or Filters directly attached to them. Instead, they are associated with a LoggerConfig. The LoggerConfig does have a setLevel method but updating it won't actually modify the level of any Loggers that use it. To do that you have to call the updateLoggers method of the LoggerContext.

LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
Configuration config = loggerContext.getConfiguration();
// Note that the next method gets the LoggerConfig that best matches the
// Logger name. If no logger 
LoggerConfig loggerConfig = config.getLoggerConfig(loggerName);
Configurator.setLevel(loggerConfig, newLevel);
loggerContext.updateLoggers();

As far as the Appenders go, Appenders are not directly attached to a LoggerConfig. Instead, they are wrapped by an AppenderControl. You can get this list of Appenders attached to a LoggerConfig by calling getAppenderRefs. You can then remove each appender one by one.

However, doing this isn't recommended. Adding and removing Appenders like this is really only there to support unit testing of Log4j. The problem is that while you are doing this the system is still logging and you are going to end up in a state where log events are lost because no appenders are configured. The recommended approach in Log4j is to create a new configuration and then do

Configurator.initialize(Configuration);

Upvotes: 4

Related Questions