WEB系统启动时加载Log4j的配置文件

来源:互联网 发布:什么是犀牛软件 编辑:程序博客网 时间:2024/05/16 16:58

在整个WEB系统中,为了统一的使用日志管理,需要在系统启动的时候就加载Log4j的配置文件,这样才能保证以后使用log4j的格式是一致的,便于跟踪和解决问题。

那么,如何在系统启动的时候加载log4j的配置文件呢?下面我简单的介绍一下:

 

1、在web.xml文件中添加一个“监听器”

<!-- 加载log4j的配置信息 -->  <listener>  <listener-class>hb.init.log4j.Log4jInit</listener-class>  </listener>

 

2、“监听类”继承“ServletContextListener”接口

package hb.init.log4j;import java.io.FileInputStream;import java.io.IOException;import java.util.Properties;import javax.servlet.ServletContext;import javax.servlet.ServletContextEvent;import javax.servlet.ServletContextListener;import org.apache.log4j.Logger;import org.apache.log4j.PropertyConfigurator;public class Log4jInit implements ServletContextListener{Logger log = Logger.getLogger(Log4jInit.class);public void contextDestroyed(ServletContextEvent sce) {log.info("Log4jInit contextDestroyed!");}public void contextInitialized(ServletContextEvent sce) {//得到servletContext对象的方法ServletContext sc = sce.getServletContext();//指明文件的相对路径就能够得到文件的绝对路径System.out.println(sc.getRealPath("/"));String path = sc.getRealPath("/config/log4j.properties");//启动服务器的时候加载日志的配置文件init(path,sc);log.info("log4j");}/** *  * @param path 配置文件的路径 * @param sc ServletContext对象 */public void init(String path,ServletContext sc){FileInputStream istream = null;try{Properties props = new Properties();//加载配置文件istream = new FileInputStream(path);props.remove("log4j.appender.file.File");System.out.println(sc.getRealPath("/log/hb.log"));//指明log文件的位置props.put("log4j.appender.file.File", sc.getRealPath("/log/hb.log"));//加载文件流,加载Log4j文件的配置文件信息props.load(istream);PropertyConfigurator.configure(props);} catch (Exception ex){try {throw new Exception(ex);} catch (Exception e) {e.printStackTrace();}} finally{try {istream.close();} catch (IOException e) {e.printStackTrace();}}}}

 

加载log4j的配置文件的目的是为了使日志文件“放在跟工程相对路径的地方”,这样即使将项目移植到不同的操作系统上面,显示也是正常的