《log4jxml配置实现.docx》由会员分享,可在线阅读,更多相关《log4jxml配置实现.docx(6页珍藏版)》请在三一办公上搜索。
1、log4jxml配置实现log4j.xml配置实现 先写一个Servlet的listener,用来监听服务启动,并自动解析log4j.xml文件 代码如下: import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.apache.log4j.LogManager; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.xml.DOMConfigurator; public
2、class Log4jConfigListener implements ServletContextListener public static final String CONFIG_LOCATION_PARAM = log4jConfigLocation; public static final String XML_FILE_EXTENSION = .xml; public void contextDestroyed(ServletContextEvent event) / TODO Auto-generated method stub LogManager.shutdown; pub
3、lic void contextInitialized(ServletContextEvent event) / TODO Auto-generated method stub String location = event.getServletContext.getInitParameter(CONFIG_LOCATION_PARAM); if (location != null) if (!location.startsWith(/) location = / + location; location = event.getServletContext.getRealPath(locati
4、on); /如果是xml结尾就用DOM解析,否则就用properties解析 if (location.toLowerCase.endsWith(XML_FILE_EXTENSION) DOMConfigurator.configure(location); else PropertyConfigurator.configure(location); 再写个util类,用来生成所要的不同类型的日志 代码如下: package com.zhaopin.util; import org.apache.log4j.Logger; public class Log4jUtil public stati
5、c Logger getSQLLogger return Logger.getLogger(sql); public static Logger getBusinessLogger return Logger.getLogger(business); public static Logger getSimpleErrorLogger return Logger.getLogger(simpleError); public static Logger getNormalErrorLogger return Logger.getLogger(normalError); 下面开始写配置文件,先要在web.xml下添加信息: log4jConfigLocation /WEB-INF/Log4j.xml Log4jConfigListener 最重要的log4j.xml的配置信息如下: - - - 在程序中应用时需要编写如下代码: Log4jUtil.getBusinessLogger.info(message!);