【问题标题】:Set log4j file path param in execution time在执行时设置 log4j 文件路径参数
【发布时间】:2012-04-10 09:55:58
【问题描述】:

在 Spring 中,我使用 slf4j 和 log4j 来解决日志记录问题。

我将相对路径放在log4j.xml配置中,但是当我在Netbeans Tomcat和独立的Apache Tomcat中执行应用程序时,相对路径不同,我必须手动更改。

我的想法是从 Spring Controller 获取上下文 realpath 并在执行时将其设置在 log4j 配置中。但我不知道...

如何从 Spring Controller 更改 log4j 的文件路径参数?

【问题讨论】:

    标签: spring log4j


    【解决方案1】:

    两个建议供您尝试:

    WebAppRootListener 添加到您的web.xml - 这将配置系统属性指向(默认为webapp.root,但您可以使用上下文参数进行自定义 - 请参阅Javadocs 链接)到您的Web 应用程序的根目录,然后您可以在 log4j.properties/xml 文件中使用它:

    <listener>
        <listener-class>org.springframework.web.util.WebAppRootListener<listener-class>
    <listener>
    
    <!-- log4.appender.File=${webapp.root}/logs/web-app.log -->
    

    或者在你的 web.xml 中使用Log4jConfigListener(最终委托给Log4jConfigurer)——这与上面类似,但允许你定义一个自定义的 log4j 配置文件,也允许你的 web 应用程序监控 log4j 配置文件在运行时所做的更改并自动更新您的记录器:

    <context-param>
        <!-- Configure Log4J from the following config file location -->
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/log4j.xml</param-value>
    </context-param>
    
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener<listener-class>
    <listener>
    

    我还建议您详细阅读上面的 Javadocs - 关于在 Tomcat 中部署多个 web 应用程序和共享系统属性有一些问题,但这都可以解决(为每个 web 应用程序提供自定义密钥,而不是默认的${webapp.root}

    【讨论】:

      猜你喜欢
      • 2020-12-11
      • 2021-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多