1.引入log4j.jar和commons-loggin.jar包,在src下新建log4j.properties文件,结构如下:
2.log4j.poperties内容配置如下:
#可以设置级别:debug>info>error
#debug:显示debug、info、error
#info:显示info、error
#error:只error
log4j.rootLogger=fetal,appender1
#log4j.rootLogger=info,appender1
#log4j.rootLogger=error,appender1
#输出到控制台
log4j.appender.appender1=org.apache.log4j.ConsoleAppender
#样式为TTCCLayout
log4j.appender.appender1.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern
= [framework] % d - % c -%- 4r [ % t] %- 5p % c % x - % m % n
3.编写测试类,如下:
package com.coderdream.log4j;
import
org.apache.commons.logging.LogFactory;
import
org.apache.commons.logging.Log;
public class HelloLog4j {
private static Log log = LogFactory.getLog("HelloLog4j.class");
/**
* @param
args
*/
public static void
main(String[] args) {
//
System.out.println("This is println
message.");
System.out.println(log.getClass());
//
记录debug级别的信息
log.debug("This is debug message.");
// 记录info级别的信息
log.info("This
is info message.");
//
记录error级别的信息
log.error("This is error message.");
log.warn("this is warn
message");
}
}
5.控制台得到结果,截图如下:
原文:http://www.cnblogs.com/zmpandzmp/p/3648801.html