log4j使用说明 [转]
1. 下载log4j解压后在目录jakarta-log4j-1.2.8dist\lib找到log4j-1.2.8.jar文件拷到
<Catalina-home>/webapps/test/WEB-INF/lib目录下
2. 创建log4j的配置文件log4j.properties,存于目录:
<Catalina-home>/webapps/test/WEB-INF
文件内容:
log4j.rootLogger=DEBUG, consoleLogger, fileLogger
log4j.appender.consoleLogger=org.apache.log4j.ConsoleAppender
log4j.appender.consoleLogger.layout=org.apache.log4j.PatternLayout
log4j.appender.consoleLogger.Threshold=DEBUG
log4j.appender.consoleLogger.layout.ConversionPattern=%c{2} - %m%n
log4j.appender.fileLogger=org.apache.log4j.RollingFileAppender
log4j.appender.fileLogger.File=c:/tomcat/webapps/test/WEB-INF/blog.txt
log4j.appender.fileLogger.MaxFileSize=1000KB
# 保留5个旧的日志文件
log4j.appender.fileLogger.MaxBackupIndex=5
log4j.appender.fileLogger.layout=org.apache.log4j.PatternLayout
# 日志格式:按照WebSphere通用日志格式相似的方式记录
log4j.appender.fileLogger.layout.ConversionPattern=[%d] %t %c %-5p - %m%n
3. 创建Blog4jServlet.java:
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class BLog4jServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
try{
String path = config.getServletContext().getRealPath("/");
String propfile = path + config.getInitParameter("propfile");
PropertyConfigurator.configure(propfile);
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
4. 修改web.xml,加入如下代码:
<servlet>
<servlet-name>log4j</servlet-name>
<servlet-class>binclude.BLog4jServlet</servlet-class>
<init-param>
<param-name>propfile</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
5. 在需要调用log的时候:
import org.apache.log4j.*;
static Logger logger = Logger.getLogger(DispatchServlet.class.getName());
logger.debug("this is a log message from" + logger.getName());
logger.info("info from" + logger.getName());
logger.warn("warn " + logger.getName());
logger.error("error" + logger.getName());