环境:
jdk8+eclipse
log4j1.2.17
在eclipse新建java工程,导入log4j的jar包。
在src目录新建文件,命名为log4j.properties。填写一下内容:
(注意:要在eclipse添加,不能直接去磁盘路径添加)
### \u8BBE\u7F6E### log4j.rootLogger = debug,stdout,D,E ### \u8F93\u51FA\u4FE1\u606F\u5230\u63A7\u5236\u62AC ### 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 ### \u8F93\u51FADEBUG \u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7\u5230=E://logs/error.log ### log4j.appender.D = org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File = D://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 ### \u8F93\u51FAERROR \u7EA7\u522B\u4EE5\u4E0A\u7684\u65E5\u5FD7\u5230=E://logs/error.log ### log4j.appender.E = org.apache.log4j.DailyRollingFileAppender log4j.appender.E.File = D://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 |
新建一个测试类:
public static void main(String[] args) {
// TODO Auto-generated method stub
Logger logger = Logger.getLogger(TestLog4j.class);
logger.error("error");
logger.info("123");
logger.debug("debug");
System.out.println(ClassLoader.getSystemResource("log4j.properties"));
System.out.println(ClassLoader.getSystemResource("log4j.xml"));
}
验证: