0
votes

I am trying to upgrade "log4j" to "log4j2 with slf4j" in project. Log4j is configured using property files. My project is divided into multiple subproject. one subproject is consist of several workflow. My target is to migrate logger one subproject wise and rest will be there with log4j. also my existing code is using log4j specific methods like "logger.getLoggerRepository()" "logger.getLevel()", "logger.log(level, logtext)" etc. Other subproject log4j is configured using "PropertyConfigurator".

I got some idea with below links but these are not helping much in my scenario:

Migrating from log4j to log4j2 - properties file configuration

Configuring log4j2 and log4j using a single log4j2 xml file

https://dzone.com/articles/log4j-2-configuration-using-properties-file

we are using below code to configure log4j using property file.

public void configureLog4j() throws IOException
{
  String path = getLog4jConfigFilePath();
  File file = new File(path);
  if (file.exists())
  {
    PropertyConfigurator.configure(path);
  }else
  {
    throw new FileNotFoundException(path);
  }
}

I tried replacing things with instruction mentioned in below official link but getting so many errors when replacing things:

https://logging.apache.org/log4j/2.x/manual/migration.html

What is the best way to migrate application in module wise so that existing code also works fine and migration can be done in iterations ?

1

1 Answers

0
votes

I found the solution and this can be achieved using LoggerContext.setConfigLocation() method, Like below :

public void configureLog4j() throws IOException
{
  String path = getLog4jConfigFilePath();
  File file = new File(path);
  if (file.exists())
  {
    LoggerContext context  = (LoggerContext)LogManager.getContext(false);
        context.setConfigLocation(file.toURI());
//      Configuration config = context.getConfiguration();
//      context.updateLoggers();
  }else
  {
    throw new FileNotFoundException(path);
  }
}

note: This will configure log4j2 on runtime using code, so while starting application you may get error for "no logger definition found".

We can define below in tomcat's "catelina.properties" file to load log4j2 definition while startup.

log4j2.configurationFile=file:///C:/location/of/log4j2.xml