Log4j,配置Web App以使用相对路径 [英] Log4j, configuring a Web App to use a relative path

查看:246
本文介绍了Log4j,配置Web App以使用相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个必须在Win或Linux机器上部署的java webapp。我现在想添加log4j用于日志记录,我想使用日志文件的相对路径,因为我不想在每次部署时更改文件路径。容器很可能是Tomcat但不一定。

I have a java webapp that has to be deployed on either Win or Linux machines. I now want to add log4j for logging and I'd like to use a relative path for the log file as I don't want to change the file path on every deployment. The container will most likely be Tomcat but not necessarily.

最好的方法是什么?

推荐答案

我终于以这种方式完成了它。

I've finally done it in this way.

添加了一个执行以下操作的ServletContextListener:

Added a ServletContextListener that does the following:

public void contextInitialized(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    System.setProperty("rootPath", context.getRealPath("/"));
}

然后在log4j.properties文件中:

Then in the log4j.properties file:

log4j.appender.file.File=${rootPath}WEB-INF/logs/MyLog.log

通过这样做,只要在设置rootPath系统属性之前不使用它,Log4j就会写入正确的文件夹。这意味着您无法从ServletContextListener本身使用它,但您应该能够在应用程序的任何其他位置使用它。

By doing it in this way Log4j will write into the right folder as long as you don't use it before the "rootPath" system property has been set. This means that you cannot use it from the ServletContextListener itself but you should be able to use it from anywhere else in the app.

它应该适用于每个Web容器和操作系统因为它不依赖于特定于容器的系统属性,并且不受操作系统特定路径问题的影响。
使用Tomcat和Orion Web容器以及Windows和Linux进行测试,到目前为止工作正常。

It should work on every web container and OS as it's not dependent on a container specific system property and it's not affected by OS specific path issues. Tested with Tomcat and Orion web containers and on Windows and Linux and it works fine so far.

您怎么看?

这篇关于Log4j,配置Web App以使用相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆