繁体   English   中英

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

[英]upgrade log4j to log4j2 with slf4j in project which configured using property files

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

我通过以下链接得到了一些想法,但这些对我的情况没有太大帮助:

从 log4j 迁移到 log4j2 - 属性文件配置

使用单个 log4j2 xml 文件配置 log4j2 和 log4j

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

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

我找到了解决方案,这可以使用 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM