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

查看:22
本文介绍了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.

这样做的最佳方法是什么?

What's the best way of doing this?

推荐答案

我终于做到了.

添加了执行以下操作的 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

通过这种方式,Log4j 将写入正确的文件夹,只要您在rootPath"系统属性设置之前不使用它.这意味着您不能从 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天全站免登陆