Log4j日志文件存放到项目目录下

时间:2022-03-24 21:48:11

方法一:直接在log4j配置中写绝对路劲


方法二:新建一个ServletContextListener的实现类Log4jConfigListener,Log4jConfigListener做:

String path = Environment.class.getResource("").getPath();
String webAppPath = path.substring(0, path.toUpperCase().lastIndexOf("WEB-INF/")).replaceAll("%20", " ");
System.setProperty("webapp",webAppPath + "logs/log.log");
在log4j配置中:
log4j.appender.A2.File=${webapp}/logs/log.log

方法三(跟Spring集成):在web.xml中配置

<context-param>
  		<param-name>webAppRootKey</param-name>  
		<param-value>webapp.root</param-value>  
	</context-param> 
	<context-param>
    	        <param-name>log4jConfigLocation</param-name>
    	        <param-value>/WEB-INF/config/log4j.properties</param-value>
  	</context-param> 
  	<context-param>
    	        <param-name>log4jRefreshInterval</param-name>
    	        <param-value>6000</param-value>
  	</context-param>
	<listener>
               <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  	</listener>

然后在log4j中用上述配置的webAppRootKey对应的值

log4j.appender.file.File=${webapp.root}/WEB-INF/logs/log.log