设置“log4j.properties”文件的绝对路径

Vit*_*lio 2 java logging log4j apache-commons-logging

我的网络应用程序使用 apache commons + log4j。

通常 log4j 需要类路径中的配置文件;但我需要将日志记录配置委托给外部文件(我需要在环境中部署 .war,但日志配置(最大大小、位置等)取决于第二个团队。

我的类路径中有一个 commons-logging.properties

org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
# log4j.configuration=/absolute/path/where/external/logs/are/log4j.properties
Run Code Online (Sandbox Code Playgroud)

不幸的是,注释行不起作用。

有没有办法使用外部配置文件设置 log4j?

小智 5

您可以将其设置为系统属性 log4j.configuration属性..例如在 J2SE 应用程序中

java -Dlog4j.configuration=file:/path/to/log4j.properties myApp
Run Code Online (Sandbox Code Playgroud)

请注意,该属性值必须是 URL。

有关更多信息,请阅读 Log4j 手册中的“默认初始化过程”部分

也可以让 ServletContextListener 设置系统属性:

import java.util.Enumeration;
import javax.servlet.*;

public class SystemPropertiesHelper implements
        javax.servlet.ServletContextListener {
    private ServletContext context = null;

    public void contextInitialized(ServletContextEvent event) {
        context = event.getServletContext();
        Enumeration<String> params = context.getInitParameterNames();

        while (params.hasMoreElements()) {
          String param = (String) params.nextElement();
          String value = 
            context.getInitParameter(param);
          if (param.startsWith("customPrefix.")) {
              System.setProperty(param, value);
          }
        }
    }

    public void contextDestroyed(ServletContextEvent event) {
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将其放入您的 web.xml 中(context.xml 也应该可以)

<context-param>
        <param-name>customPrefix.property</param-name>
        <param-value>value</param-value>
        <param-type>java.lang.String</param-type>
</context-param>

<listener>
    <listener-class>servletUtils.SystemPropertiesHelper</listener-class>    
</listener>
Run Code Online (Sandbox Code Playgroud)

我从answer的侦听器代码中得到了这个 。

我希望这可以帮助你!