Log4j is a sub-project of open source code under Jakarta, with log4j, we can use the custom format to output debug information and log information to one or more needed places. In a Web application, a dedicated servlet is typically used to complete the configuration of the log4j and to ensure that the servlet is in the configuration of the. xml, before other Servlets, for invocation in Servlets and JSPs. Here is the servlet with the following code:
package example;
Import org.apache.log4j.*;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
public class Log4jinit extends HttpServlet {
public void init () {
String prefix = Getservletcontext (). Getrealpath ("/");
String file = Getinitparameter ("log4j");//configuration file location
if (file! = null) {
Propertyconfigurator.configure (Prefix+file);
}
}
public void Doget (HttpServletRequest req,
HttpServletResponse res) {}
}
This servlet is configured in Web. XML:
</web-app>
...........
Servlet>
<servlet-name>log4j-init</servlet-name>
<servlet-class>example. 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>
...........
</web-app>
The properties file used to configure log4j:
Log4j.rootlogger=debug, A1, R
Log4j.appender.a1=org.apache.log4j.consoleappender
Log4j.appender.a1.layout=org.apache.log4j.patternlayout
Log4j.appender.a1.layout.conversionpattern=%-d{yyyy-mm-dd HH:MM:SS} [%c]-[%p]%m%n
Log4j.appender.r=org.apache.log4j.rollingfileappender
Log4j.appender.r.file=cwblog4j.log
log4j.appender.r.maxfilesize=100kb
Log4j.appender.r.maxbackupindex=1
Log4j.appender.r.layout=org.apache.log4j.patternlayout
log4j.appender.r.layout.conversionpattern=%p%t%c-%m%n
This configuration file specifies two output sources A1 and R. The former outputs log information to the console, which is a Web log file. The largest file is 100KB, and when a log file reaches its maximum size, log4j automatically renames the Example.log to Example.log.1, then rebuilds a new Example.log file, rotating it in turn.
Test file:
<%@ page contenttype= "text/html; charset=gb2312 "%>
<%@ page import= "org.apache.log4j.*"%>
<%
Logger Logger = Logger.getlogger ("test.jsp");
Logger.debug ("befor say hi");
%>
<% Logger.info ("After say hi");%>
You see the following information in the $tomcat_home/log4j.log file on the server:
DEBUG Thread-5 testlog4j.jsp-befor say hi
INFO Thread-5 testlog4j.jsp-after say hi
At the end of the $tomcat_home/logs/stdout.log file there is the following output.
Info: Server Startup in 5678 MS
2004-07-07 09:54:05 [testlog4j.jsp]-[debug] befor say hi
2004-07-07 09:54:05 [Testlog4j.jsp]-[info] after say hi
Using logs in a web App