使用属性文件配置的项目中的slf4j将log4j升级到log4j2

问题描述 投票:0回答:1

我正在尝试在项目中将“ log4j”升级为“带有slf4j的log4j2”。使用属性文件配置Log4j。我的项目分为多个子项目。一个子项目由多个工作流程组成。我的目标是明智地将记录器迁移到一个子项目,其余部分将与log4j一起存在。我现有的代码也使用了log4j的特定方法,例如“ logger.getLoggerRepository()”,“ logger.getLevel()”,“ logger.log(level,logtext)”等。其他子项目log4j是使用“ PropertyConfigurator”配置的。

我对以下链接有一些了解,但在我的情况下这些链接没有太大帮助:

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

我们正在使用以下代码使用属性文件来配置log4j。

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

我尝试用下面官方链接中提到的说明替换事物,但是在替换事物时出现了很多错误:

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

以模块方式迁移应用程序的最佳方法是什么,以便现有代码也可以正常工作并且可以在迭代中完成迁移?

java tomcat log4j log4j2 slf4j
1个回答
0
投票

我找到了解决方案,可以使用LoggerContext.setConfigLocation()方法实现,如下所示:

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);
  }
}

注意:这将使用代码在运行时配置log4j2,因此在启动应用程序时,您可能会因“找不到记录器定义”而出错。

我们可以在tomcat的“ catelina.properties”文件中定义以下内容,以在启动时加载log4j2定义。

log4j2.configurationFile=file:///C:/location/of/log4j2.xml
© www.soinside.com 2019 - 2024. All rights reserved.