1.lo4j日志路径从环境变量读取,log4j.xml配置如下:
具体配置如下:
log4j.appender.R.Encoding=UTF-8
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.Append=true
#log4j.appender.R.Threshold=INFO
log4j.appender.R.File=${log4j.home}/logs/log.log
log4j.appender.R.DatePattern='.'yyyy-MM-dd
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n
1.1 监听配置web.xml
<listener> <listener-class>com.jumper.logview.servlet.Log4jlistener</listener-class> </listener>
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加载配置
<context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/classes/config/log4j.properties</param-value> </context-param> <!-- Spring刷新Log4j配置文件变动的间隔,单位为毫秒 --> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>1000000</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener>
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. <br> * * @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配置: <servlet> <servlet-name>Log4jInit</servlet-name> <servlet-class>com.jumper.log4j.Log4jInit</servlet-class> <init-param> <param-name>log4j</param-name>//这个是名字是下边路径配置的标识(好像KEY一样) <param-value>/WEB-INF/classes/config/log4j.properties</param-value>//这是容器初始化时候加载log4j配置文件的路径(这好像一个value); </init-param> <load-on-startup>1</load-on-startup> </servlet>