1.lo4j日志路径从环境变量读取,log4j.xml配置如下:
具体配置如下:log4j.appender.R.Encoding=UTF-8log4j.appender.R=org.apache.log4j.DailyRollingFileAppenderlog4j.appender.R.Append=true#log4j.appender.R.Threshold=INFOlog4j.appender.R.File=${log4j.home}/logs/log.loglog4j.appender.R.DatePattern='.'yyyy-MM-ddlog4j.appender.R.layout=org.apache.log4j.PatternLayoutlog4j.appender.R.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss} [%c]-[%p] %m%n
1.1 监听配置web.xml
com.jumper.logview.servlet.Log4jlistener
1.2 监听代码
public class Log4jlistener implements ServletContextListener { final static String LOG4J_HOME = "log4j.home"; final static String ENV_HOME = "LOG4J_HOME"; public void contextDestroyed(ServletContextEvent servletcontextevent) { System.getProperties().remove(LOG4J_HOME); } public void contextInitialized(ServletContextEvent servletcontextevent) { String logsHome = System.getenv(ENV_HOME); if(logsHome == null){ logsHome = System.getProperty("catalina.home")+"/log4j"; }System.out.println("*********log4j dir:"+logsHome); System.setProperty(LOG4J_HOME, logsHome); }}
2.log4j 加载的两种方式
2.1采用spring加载配置
log4jConfigLocation /WEB-INF/classes/config/log4j.properties log4jRefreshInterval 1000000 org.springframework.web.util.Log4jConfigListener
2.2采用serlvet加载
import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import org.apache.log4j.PropertyConfigurator;public class Log4jInit extends HttpServlet { private static final long serialVersionUID = 1L; public void destroy() { super.destroy(); } public Log4jInit() { super(); } /** * Initialization of the servlet. * * @throws ServletException * if an error occurs */ public void init() throws ServletException { String file = this.getInitParameter("log4j");// 从web.xml配置读取,名字一定要和web.xml配置一致 if (file != null) { PropertyConfigurator.configure(this.getServletContext().getRealPath(file)); } }}web.xml配置:Log4jInit com.jumper.log4j.Log4jInit log4j //这个是名字是下边路径配置的标识(好像KEY一样)/WEB-INF/classes/config/log4j.properties //这是容器初始化时候加载log4j配置文件的路径(这好像一个value);1