1、新建一个Java工程,导入包log4j-1.2.17.jar。
2、src同级创建并设置log4j.properties,内容如下
### 设置### log4j.rootLogger = debug,stdout,D,E ### 输出信息到控制抬 ### log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.appender.stdout.layout = org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n ### 输出DEBUG 级别以上的日志到=E://logs/error.log ### log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = E://logs/log.log log4j.appender.D.Append = true log4j.appender.D.Threshold = DEBUG log4j.appender.D.layout = org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n ### 输出ERROR 级别以上的日志到=E://logs/error.log ### log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File =E://logs/error.log log4j.appender.E.Append = true log4j.appender.E.Threshold = ERROR log4j.appender.E.layout = org.apache.log4j.PatternLayout log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
3、设置日志内容
package com.log4jTest; import org.apache.log4j.Logger; public class Test { private static Logger logger = Logger.getLogger(Test.class); public static void main(String[] args) { // 记录debug级别的信息 logger.debug("This is debug message."); // 记录info级别的信息 logger.info("This is info message."); // 记录error级别的信息 logger.error("This is error message."); } }
控制台输出结果
[DEBUG] 2016-08-14 14:30:19,852 method:com.log4jTest.Test.main(Test.java:34) This is debug message. [INFO ] 2016-08-14 14:30:19,858 method:com.log4jTest.Test.main(Test.java:36) This is info message. [ERROR] 2016-08-14 14:30:19,858 method:com.log4jTest.Test.main(Test.java:38) This is error message.
log.log文件输出结果
2016-08-14 14:47:23 [ main:0 ] - [ DEBUG ] This is debug message. 2016-08-14 14:47:23 [ main:5 ] - [ INFO ] This is info message. 2016-08-14 14:47:23 [ main:5 ] - [ ERROR ] This is error message.
error.log文件输出结果
2016-08-14 14:47:23 [ main:5 ] - [ ERROR ] This is error message.