保存Log4j日志文件到指定路径

第一种方法:


1、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>classpath: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>


log4jRefreshInterval为60000表示 开一条watchdog线程每60秒扫描一下配置文件的变化; 


2、配置文件log4j.properties  文件地址写为:

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


第二种方法:

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

示例:

package com.spring.base;

import javax.servlet.ServletContextEvent;
import javax.servlet.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.setProperty(log4jdirkey, log4jdir);
    }
}

2、配置web.xml

添加如下代码:

<listener>
<listener-class>com.spring.base.log4jlistener</listener-class>
</listener>

3、配置文件log4j.properties  文件地址写为

log4j.appender.E.File = ${log4jdir}/WEB-INF/logs/error.log


猜你喜欢

转载自blog.csdn.net/tolcf/article/details/50914496