log4j设置默认日志目录

时间:2015-05-22 22:27:40

标签: log4j

我的桌面应用程序使用log4j 1.2.17。
我允许通过属性文件进行配置,这样用户可以设置他们想要的多个日志输出。
在生产中,我有一个特定的日志目录,位于/var/myapp/log目录下。
在开发中,我有一个特定的日志目录,在/users/agostino/development/myapp/devenvironment/log下,这使我可以轻松地进行自动化测试,因为所有的东西都在一个地方。
在log4j.properties中我有这样一行:

log4j.appender.default_file.File=example.log

好吧,正如我所说,这应该在指定的日志目录中,/var/myapp/log在生产时或/users/agostino/development/myapp/devenvironment/log我正在开发中。

我只能考虑在属性中进行一些搜索和替换,即使这样也会有点麻烦。有更干净的方法吗? 我不想使用插值,因为它应该对用户透明。

2 个答案:

答案 0 :(得分:3)

我认为解决问题的一种方法是在虚拟机启动时使用参数。 e.g:

java -Dcustom.log.file=/var/myapp/log ...

您在配置文件中使用该系统属性。 e.g:

log4j.appender.default_file.File=${custom.log.file}/example.log

答案 1 :(得分:1)

你可以通过使用听众来实现它。

示例代码:

public class Log4jListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {

        ServletContext context = sce.getServletContext();
        System.setProperty("rootPath", context.getRealPath(File.separator));

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }

}

在上面的代码中,已部署的路径设置为系统属性。使用 $ {rootPath}

在log4j.xml中访问它

- 您必须在web.xml中声明该侦听器

<!-- listener to set  deployed path to logger -->
  <listener>
        <listener-class>a.b.c.Log4jListener</listener-class>
    </listener>
相关问题