log4j日志文件输出到项目根目录
在使用log4j进行日志文件输出时,并不能够默认输出到项目根目录,或者输出到相对路径,只能输出到绝对路径。
经修改配置文件得到有效解决:
1.配置监听器
通过监听器获取项目绝对路径,并且配置系统属性变量
String log4jDir=arg0.getServletContext().getRealPath("/");
System.setProperty("log4jDirKey", log4jDir);
package com.wd.listener;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class applicationListener implements ServletContextListener,ServletContextAttributeListener{
@Override
public void contextDestroyed(ServletContextEvent arg0) {
System.getProperties().remove("log4jDirKey");
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
String log4jDir=arg0.getServletContext().getRealPath("/");
System.setProperty("log4jDirKey", log4jDir);
}
}
2.配置lolog4j.properties
使用${log4jDirKey}获取项目根目录,并且配置到log4j.properties中
log4j.rootCategory=ERROR, CONSOLE,LOGFILE
log4j.logger.com.wd.mapper.PeopleMapper=DEBUG
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=-%p-%d{yyyy/MM/dd HH:mm:ss,SSS}-%l-%L-%m%n
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=${log4jDirKey}/myLogs.log
log4j.appender.LOGFILE.Append=false
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=-%p-%d{yyyy/MM/dd HH:mm:ss,SSS}-%l-%L-%m%n