我的桌面应用程序使用log4j 1.2.17。
我允许通过属性文件进行配置,这样用户就可以设置他们想要的任意数量的日志输出。
在生产中,我有一个位于
/var/myapp/log
目录下的特定日志目录。 /users/agostino/development/myapp/devenvironment/log
下的特定日志目录,它允许我轻松地进行自动化测试,因为所有内容都在一个地方。 log4j.appender.default_file.File=example.log
嗯,正如我所说,这应该放在指定的日志目录中,即生产中的
/var/myapp/log
或开发中的 /users/agostino/development/myapp/devenvironment/log
。 我认为解决问题的一种方法是在虚拟机启动时使用参数。例如:
java -Dcustom.log.file=/var/myapp/log ...
您可以在配置文件中使用该系统属性。例如:
log4j.appender.default_file.File=${custom.log.file}/example.log
您可以通过使用监听器来实现。
示例代码:
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>