1.创建commons-logging的配置文件commons-logging.properties置于代码的根目录下,并指定使用Log4J的Logger
org.apache.commons.logging.Log=org.apache.commons.logging.impl.Log4JLogger
2.创建Log4J的配置文件log4j.properties置于代码的根目录下
#using log4j 1.2.x
#root Logger for all class
log4j.rootLogger=DEBUG,console,logfile
#Logger for specific class
#log4j.logger.common.Log4J=DEBUG,console,logfile
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.Target=System.out
log4j.appender.console.Encoding=GBK
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d %p [%F] [%t] [line %L in %c] - %m%n
#this type of Appender will create log file everyday
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.DatePattern='.'yyyy-MM-dd
log4j.appender.logfile.File=logs/testLog.log
log4j.appender.logfile.Append=true
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%F] [%t] [%L] [%c] - %m%n
# %d = time
# %p = level
# %F = class name
# %t = method name
# %L = line number in class
# %c = class name(include package)
# %m = message
# %n = new line
3.测试代码
package common;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class Log4J {
private static Log logger = LogFactory.getLog(Log4J.class);
/**
* @param args
*/
public static void main(String[] args) {
if(logger.isInfoEnabled())logger.info("this is message");
logger.error("error");
System.out.println("hello");
}
}