Java web 应运中,一般情况下,只需将log4j的配置文件** log4j.properties**或者 **log4j.xml**放置在web的根目录下(WEB-INF\classes ),我们就可以便捷的以如下方式使用_log4j_:
Logger logger = Logger.getLogger(MyServlet.class);
logger.debug("this is a debug log message");
如果将_log4j_的配置文件,放置在web 应用的其它目录下,则需要显示的以如下方式初始化_log4j_:
String log4jConfigFile = "some/path/log4j.properties";
PropertyConfigurator.configure(log4jConfigFile);
这种初始化方式只会在web应运启动的时候执行一次,推荐的方法是实现_ServletContextListener接口,在contextInitialized()_事件中实现初始化:
public class ContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
// code to initialize log4j here...
}
}
以下是在_Java Web应用程序中初始化和使用log4j_的步骤:
1. 创建 _log4j.properties_文件
# LOG4J configuration
log4j.rootLogger=DEBUG, Appender1,Appender2
log4j.appender.Appender1=org.apache.log4j.ConsoleAppender
log4j.appender.Appender1.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender1.layout.ConversionPattern=%-7p %d [%t] %c %x - %m%n
log4j.appender.Appender2=org.apache.log4j.FileAppender
log4j.appender.Appender2.File=D:/Logs/Log4jWebDemo.log
log4j.appender.Appender2.layout=org.apache.log4j.PatternLayout
log4j.appender.Appender2.layout.ConversionPattern=%-7p %d [%t] %c %x - %m%n
该配置文件创建了两个基本的 appender,第一个是_ConsoleAppender,第二个FileAppender_(日志记录将会输出至 D:/Logs/Log4jWebDemo.log)
将_log4j.properties_放在 _WEB-INF_下
2.在web.xml文件里配置log4j.properties文件位置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Log4jWebDemo1</display-name>
<context-param>
<param-name>log4j-config-location</param-name>
<param-value>WEB-INF/log4j.properties</param-value>
</context-param>
</web-app>
3.实现ServletContextListener接口
用如下代码创建一个实现了**ServletContextListener** 接口的类**ContextListener**
package net.codejava.servlet;
import java.io.File;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.apache.log4j.PropertyConfigurator;
@WebListener("application context listener")
public class ContextListener implements ServletContextListener {
/**
* Initialize log4j when the application is being started
*/
@Override
public void contextInitialized(ServletContextEvent event) {
// initialize log4j here
ServletContext context = event.getServletContext();
String log4jConfigFile = context.getInitParameter("log4j-config-location");
String fullPath = context.getRealPath("") + File.separator + log4jConfigFile;
PropertyConfigurator.configure(fullPath);
}
@Override
public void contextDestroyed(ServletContextEvent event) {
// do nothing
}
}
在_contextInitialized()_方法中,我们读取并构建了**log4j.properties绝对路径,使用 PropertyConfigurator.configure() 对log4j用指定的properties**文件进行了初始化。
note:
在Servlet 3.0 才支持** @WebListener注解,如果你使用的是Servlet 2.5**,请在web.xml中使用如下等价的配置:
<listener>
<listener-class>net.codejava.servlet.ContextListener</listener-class>
</listener>
4.创建一个测试类
package net.codejava.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
@WebServlet("/test")
public class TestLog4jServlet extends HttpServlet {
static final Logger LOGGER = Logger.getLogger(TestLog4jServlet.class);
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
LOGGER.info("This is a logging statement from log4j");
String html = "<html><h2>Log4j has been initialized successfully!</h2></html>";
response.getWriter().println(html);
}
}
同样如果你的web不支持Servlet 3.0,请在web.xml加入如下等价的配置:
<servlet>
<display-name>TestServlet</display-name>
<servlet-name>TestServlet</servlet-name>
<servlet-class>net.codejava.servlet.TestLog4jServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
5. 测试
启动web应用输入如下地址:
可以在控制台和** D:/Logs**下看到相关日志的输出