Log4j 配置檔案
阿新 • • 發佈:2018-12-19
log4j.rootLogger=DEBUG,AA,BB log4j.appender.AA=org.apache.log4j.ConsoleAppender log4j.appender.AA.Target=System.err log4j.appender.AA.layout=org.apache.log4j.SimpleLayout log4j.appender.BB=org.apache.log4j.FileAppender log4j.appender.BB.File=BookShop.log log4j.appender.BB.layout=org.apache.log4j.PatternLayout log4j.appender.BB.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %l %F %p %m%n
其中:aa--->log日誌列印到控制檯上;
bb--->列印到tomcat/bin/BookShop.log資料夾裡
如果想將日誌儲存到web-inf下 有以下四種方式
1. 絕對路徑
log4j.appender.A1.File=D:\apache-tomcat-6.0.18/webapps/專案/WEB-INF/logs/app.log
這種寫法靈活性很差
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檔案。
3.使用已有jvm變數:
例如:
log4j.appender.logfile.File=${user.home}/logs/app.log
日誌將位於:例如windows:C:\Documents and Settings\joe\logs\app.log
自己設定目錄,也就是在專案啟動時通過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 來解決。