如何用另一个log4j2配置文件覆盖一个log4j2配置文件?

如何用另一个log4j2配置文件覆盖一个log4j2配置文件?,log4j,log4j2,Log4j,Log4j2,我当前的web应用程序使用log4j1.2,我想迁移到log4j2,但我还没有弄清楚如何处理我的特定用例 在我的web应用程序的war文件中,我存储了一个具有合理默认值的log4j配置文件。我的设计是搜索war文件外部的配置文件,该文件将覆盖与war捆绑的配置。这样,在部署时配置日志记录配置,并且每个服务器的日志记录配置可能不同 使用log4j 1.2,这是通过ServletContextListener通过以下方法实现的,它非常有效: /** * Configures system-wide

我当前的web应用程序使用log4j1.2,我想迁移到log4j2,但我还没有弄清楚如何处理我的特定用例

在我的web应用程序的war文件中,我存储了一个具有合理默认值的log4j配置文件。我的设计是搜索war文件外部的配置文件,该文件将覆盖与war捆绑的配置。这样,在部署时配置日志记录配置,并且每个服务器的日志记录配置可能不同

使用log4j 1.2,这是通过ServletContextListener通过以下方法实现的,它非常有效:

/**
 * Configures system-wide log4j logging system with log4j.xml from the
 * class path.  This overrides configuration from the default location in
 * Tomcat:  WEB-INF/classes
 */
private void configureLog4J() {
    URL url = ClassLoader.getSystemResource("log4j.xml");
    if (url != null) {
        DOMConfigurator.configure(url);
        log = org.apache.log4j.LogManager.getLogger(LDSContextListener.class);
        log.info("log4j.xml loaded from " + url);
    }
}

如果要迁移到log4j2,如何使用外部文件的配置覆盖内部文件?log4j2的API中没有
DOMConfigurator

我建议您在log4j2 Jira问题跟踪器上创建一个功能请求。

我找到了一个解决方案,它并没有完全复制我以前的解决方案,但已经足够接近了

我没有以编程方式配置log4j,而是将
log4j-web-2.0.jar
添加到我的类路径中,并将以下内容添加到我的web.xml中:

<context-param>
  <param-name>isLog4jAutoInitializationDisabled</param-name>
  <param-value>true</param-value>
</context-param>
<context-param>
  <param-name>log4jConfiguration</param-name>
  <param-value>file:///usr/jboss/ldsconf/log4j2.xml</param-value>
</context-param>

<listener>
  <listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
</listener>

<filter>
  <filter-name>log4jServletFilter</filter-name>
  <filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>log4jServletFilter</filter-name>
  <url-pattern>/*</url-pattern>
  <dispatcher>REQUEST</dispatcher>
  <dispatcher>FORWARD</dispatcher>
  <dispatcher>INCLUDE</dispatcher>
  <dispatcher>ERROR</dispatcher>
  <dispatcher>ASYNC</dispatcher><!-- Servlet 3.0 w/ disabled auto-initialization only; not supported in 2.5 -->
</filter-mapping>

isLog4jAutoInitializationDisabled
真的
Log4J配置
file:///usr/jboss/ldsconf/log4j2.xml
org.apache.logging.log4j.web.Log4jServletContextListener
log4jServletFilter
org.apache.logging.log4j.web.Log4jServletFilter
log4jServletFilter
/*
要求
向前地
包括
错误
异步的
其中log4jConfiguration
context参数
指定我的外部配置文件的位置。这与类加载器在类路径中搜索配置文件不同,但它仍然允许我引用外部配置文件。另外,如果这个文件不存在,系统将返回到内部配置文件,这正是我想要的


参考:

您可以在启动应用程序时添加名为LOG4J_CONFIGURATION_FILE的环境变量