新建Servlet并加入以前方法
public void init() throws ServletException {
String prefix = getServletContext().getRealPath( "/"); //空间根目录,绝对路径
String file = getInitParameter("log4j"); //加载Log4j配置文件
// if the log4j-init-file is not set, then no point in trying
System.out.println( "................log4j start ");
if(file != null) {
PropertyConfigurator.configure(prefix+file); //加载失败启用Log4j默认配置
System.out.println(prefix+file);
}
System.out.println(getServletContext().getRealPath("/"));
//设置系统环境
System.setProperty("webapp.root", getServletContext().getRealPath("/"));
}
配置web.xml
<servlet>
<servlet-name>log4j-init</servlet-name>
<servlet-class>com.log4j.Log4jInit</servlet-class>
<init-param>
<param-name>log4j</param-name>
<param-value>WEB-INF/log4j.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>