Eclipse新建Java工程,工程目录如下
1、下载log4j的Jar包,在Java工程下新建lib文件夹,将jar包拷贝到此文件夹,并将其加入到路径中,即:Jar包上右键——Build Path——Add to Build Path
2、src文件夹下新建log4j.properties文档,内容如下:
log4j.rootLogger=info, stdout, log, errorlog
log4j.Logger=search,Test
###Console ###
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 = %d{ABSOLUTE} [ %t ] [ %p ]:%L - %m%n
### Log ###
log4j.appender.log = org.apache.log4j.DailyRollingFileAppender
log4j.appender.log.File = log/log.log
log4j.appender.log.Append = true
log4j.appender.log.Threshold = INFO
log4j.appender.log.DatePattern='.'yyyy-MM-dd
log4j.appender.log.layout = org.apache.log4j.PatternLayout
log4j.appender.log.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t ] %m%n
### Error ###
log4j.appender.errorlog = org.apache.log4j.DailyRollingFileAppender
log4j.appender.errorlog.File = log/errorlog.log
log4j.appender.errorlog.Append = true
log4j.appender.errorlog.Threshold = ERROR
log4j.appender.errorlog.DatePattern='.'yyyy-MM-dd
log4j.appender.errorlog.layout = org.apache.log4j.PatternLayout
log4j.appender.errorlog.layout.ConversionPattern =%-d{yyyy-MM-dd HH:mm:ss} [ %t ] %m%n
3、Java工程中新建log文件夹,并建立log.log和errorlog.log两个文档,存放日志
4、src文件夹下新建LogTest类,测试效果:
import org.apache.log4j.Logger;
public class LogTest {
public static void main(String[] args) {
Logger logger = Logger.getLogger(LogTest.class);
logger.info("wangxiaodong");
logger.error("this is error");
}
}
然后,可以看到log.log和errorlog.log文档中有日志了
参考:
http://www.codeceo.com/article/log4j-usage.html