温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

详解Log4j 日志文件存放位置设置

发布时间:2020-10-20 18:04:44 来源:脚本之家 阅读:228 作者:擦肩而过 栏目:编程语言

以DailyRollingFileAppender 为例:假设每天一个日志文件

有以下设置:

log4j.appender.A1=org.apache.log4j.DailyRollingFileAppender

log4j.appender.A1.File=app.log

log4j.appender.A1.DatePattern='.'yyyy-MM-dd

log4j.appender.A1.layout=org.apache.log4j.PatternLayout

log4j.appender.A1.layout.ConversionPattern=%d %5p - %c -%-4r [%t]    - %m%n

经过自己测试,无法找到app.log文件 

如要将日志文件保存在 :根目录/web-info/logs/下,个人有以下4种解决方案:

1 绝对路径

log4j.appender.A1.File=D:\apache-tomcat-6.0.18/webapps/项目/WEB-INF/logs/app.log

但这种写法灵活性很差

以下3中使用相同的设置原理: jvm的环境变量

2:spring的Log4jConfigListener

通过以下配置

<context-param> 
  <param-name>webAppRootKey</param-name> 
  <param-value>webApp.root</param-value> 
 </context-param> 
 <context-param> 
 <param-name>log4jConfigLocation</param-name> 
  <param-value>classpath:log4j.properties</param-value> 
 </context-param> 
<listener>  
   <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  
 </listener> 

log4j.appender.logfile.File=${webApp.root}/WEB-INF/logs/app.log

备注:

1、spring配置变了webAppRootKey是不能变的,值可以随意写。

2、log文件存放在tomcat工程目录/webapp(工程名称)/WEB-INF/logs/app.log文件。

2:使用已有jvm变量:

例如:

log4j.appender.logfile.File=${user.home}/logs/app.log

日志将位于:例如windows:C:\Documents and Settings\joe\logs\app.log

3 自己设置目录,也就是在项目启动时通过System.setProperty设置,通过实现ServletContextListener来解决:例如

public class log4jlistener implements ServletContextListener { 
  public static final String log4jdirkey = "log4jdir"; 
  public void contextDestroyed(ServletContextEvent servletcontextevent) { 
    System.getProperties().remove(log4jdirkey); 
  } 
  public void contextInitialized(ServletContextEvent servletcontextevent) { 
  String log4jdir = servletcontextevent.getServletContext().getRealPath("/"); 
  //System.out.println("log4jdir:"+log4jdir); 
  System.setProperty(log4jdirkey, log4jdir); 
  } 
} 

web.xml配置:

<listener> 
  <listener-class>com.log4j.log4jlistener</listener-class> 
</listener> 

log4j.prtperties 配置:

log4j.appender.A1.File=${log4jdir}/WEB-INF/logs/app1.log 来解决。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI