
先写一个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 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();
}
public 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(location);
//如果是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 static 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下添加信息:
最重要的log4j.xml的配置信息如下:
在程序中应用时需要编写如下代码:
Log4jUtil.getBusinessLogger().info("message!");
