1、引入jar包:log4j-1.2.14.jar
2、在WEB-INF目录下新建文件log4j.properties
3、在log4j.properties配置相关信息如下:
#rootConfig
log4j.rootLogger=DEBUG, Console, RollingFile,SingleFile
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p [%c] - %m%n
#RollingFile
log4j.appender.RollingFile=org.apache.log4j.RollingFileAppender
log4j.appender.RollingFile.File=..//webapps//TestLog4j//logs//debug.txt // 注意是Tomcat目录下,不一定是工程所在位置
log4j.appender.RollingFile.MaxFileSize=10MB
log4j.appender.RollingFile.MaxBackupIndex=10
log4j.appender.RollingFile.Threshold = DEBUG
log4j.appender.RollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.RollingFile.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} [%t] %-5p [%c] - %m%n
#SingleFile
log4j.appender.SingleFile = org.apache.log4j.FileAppender
log4j.appender.SingleFile.File=..//webapps//TestLog4j//logs//error.txt
log4j.appender.SingleFile.Threshold = ERROR
log4j.appender.SingleFile.layout=org.apache.log4j.HTMLLayout
4、创建测试Servlet(LogShow.java)
// LogShow.java
public class LogShow extends HttpServlet {
public void init(){
String prefix = getServletContext().getRealPath("/");
}
public void doGet(HttpServletRequest req, HttpServletResponse res) {
Logger logger = Logger.getLogger(LogShow.class);
logger.debug("调试");
logger.error("错误信息");
}
}
// web.xml
<!--