很简单,我喜欢将Log跟着webRoot走,这样随便你项目移到哪,都可以直接运行,不要再运行这运行那。
思路是写一个初始化log4j的servlet。
public class Log4jInit extends HttpServlet {
static Logger logger = Logger.getLogger(Log4jInit.class);
public Log4jInit() {
}
public void init(ServletConfig config) throws ServletException {
String prefix = config.getServletContext().getRealPath("/");
String file = config.getInitParameter("log4j");
String filePath = prefix + file;
Properties props = new Properties();
try {
FileInputStream istream = new FileInputStream(filePath);
props.load(istream);
istream.close();
//toPrint(props.getProperty("log4j.appender.file.File"));
String logFile = prefix + props.getProperty("log4j.appender.file.File");//设置路径
props.setProperty("log4j.appender.file.File",logFile);
PropertyConfigurator.configure(props);//装入log4j配置信息
} catch (IOException e) {
toPrint("Could not read configuration file [" + filePath + "].");
toPrint("Ignoring configuration file [" + filePath + "].");
return;
}
}
public static void toPrint(String content) {
System.out.println(content);
}
}
refurl:http://sharep.blog.51cto.com/539048/143734
http://ziqiang0501.iteye.com/blog/280755 ,有spring的配置,具体如下:
由于spring也会加载log4j.properties,如果加载不到就往控制台打log信息,总觉得有些碍眼,于是想办法去掉。Spring提供了一个Log4jConfigListener,本身就能通过web.xml中配置来指定位置加载log4j配置文件和log输出路径,注意该listener需要放在spring的Listener之前。
事实上,Log4jConfigListener更适合log4j在web工程中使用,原因如下:
1. 动态的改变记录级别和策略,不需要重启Web应用,如《Effective Enterprise Java》所说。
2. 把log文件定在 /WEB-INF/logs/ 而不需要写绝对路径。
因为 系统把web目录的路径压入一个叫webapp.root的系统变量。这样写log文件路径时不用写绝对路径了.
log4j.appender.logfile.File=${webapp.root}/WEB-INF/logs/myfuse.log
3. 可以把log4j.properties和其他properties一起放在/WEB-INF/ ,而不是Class-Path。
4.log4jRefreshInterval为60000表示 开一条watchdog线程每60秒扫描一下配置文件的变化;
在web.xml 添加
<context-param> <param-name>log4jConfigLocation</param-name> <param-value>WEB-INF/log4j.properties</param-value> </context-param> <context-param> <param-name>log4jRefreshInterval</param-name> <param-value>60000</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener>