我们在编写代码的时候有各种需要打印日志的需求,这里记录一下如何使用log4j记录日志。
我的项目都是使用maven来管理的,所以只要在pom.xml文件中添加以下内容即可:
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>org.lazyluke</groupId>
<artifactId>log4jdbc-remix</artifactId>
<version>0.2.7</version>
</dependency>
在src下的任意位置新建log4j.properties,内容如下:
log4j.rootLogger=debug, file, stdout,E
log4j.logger.org.apache=error
log4j.logger.org.springframework=error
log4j.logger.org.quartz=error
log4j.logger.org.hibernate=error
log4j.logger.net.sf.ehcache=error
log4j.logger.com.mchange.v2.resourcepool.BasicResourcePool=ERROR,C1
log4j.appender.C1=org.apache.log4j.RollingFileAppender
log4j.appender.C1.File=./c3p0.log
log4j.appender.C1.MaxFileSize=500KB
log4j.appender.C1.MaxBackupIndex=100
log4j.appender.C1.layout=org.apache.log4j.PatternLayout
log4j.appender.C1.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%c]-[%L] %m%n
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.Encoding=UTF-8
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %c:%L ] %m%n
log4j.appender.logger = org.apache.log4j.DailyRollingFileAppender
log4j.appender.logger.File = logs/log.log
log4j.appender.logger.Encoding=UTF-8
log4j.appender.logger.Append = true
log4j.appender.logger.Threshold = DEBUG
log4j.appender.logger.layout = org.apache.log4j.PatternLayout
log4j.appender.logger.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %c:%L ] %m%n
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.File=./log/server.log
log4j.appender.file.Encoding=UTF-8
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %c:%L ] %m%n
log4j.appender.E=org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File=./log/server.err.log
log4j.appender.E.layout=org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [ %c:%L ] %m%n
log4j.appender.E.Threshold = ERROR
这里的配置内容网上已经有比较全面的介绍
连接:http://blog.csdn.net/chen3749102/article/details/52224457
使用:
在类中定义一个静态全局变量,并传入自身的类型,这是为了输出的日志中能看到内容的来源:
public class App
{
static final Logger logger = LoggerFactory.getLogger(App.class);
public static void main( String[] args )
{
logger.info( "info test" );
logger.error("error test");
}
}
运行程序就可以在控制台中看到我们输出的内容:
同时可以看到项目目录中已经多出了一个log文件夹,并生成了2个log文件,其中保存了我们的输出内容: