首页 > 代码库 > log4j 简单用法

log4j 简单用法

maven添加必要库:

1         <!-- https://mvnrepository.com/artifact/log4j/log4j -->
2         <dependency>
3             <groupId>log4j</groupId>
4             <artifactId>log4j</artifactId>
5             <version>1.2.17</version>
6         </dependency>

在web.xml中添加监听:

1     <listener>
2         <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
3     </listener>

log4j.properties配置文件放在classpath路径下:

 1 log4j.rootLogger=info,stdout,D
 2 log4j.appender.stdout=org.apache.log4j.ConsoleAppender
 3 log4j.appender.stdout.Target=System.out
 4 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
 5 log4j.appender.stdout.layout.ConversionPattern= %d{ABSOLUTE} %5p %c{1}:%L - %m%n
 6 log4j.appender.D=org.apache.log4j.DailyRollingFileAppender
 7 log4j.appender.D.Threshold=warn
 8 log4j.appender.D.File=${webapp.root}/WEB-INF/logs/log
 9 log4j.appender.D.DatePattern=‘_‘yyyy-MM-dd‘.log‘
10 log4j.appender.D.Append=true
11 log4j.appender.D.layout=org.apache.log4j.PatternLayout
12 log4j.appender.D.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%t:%r] - [%p]  %m%n
log4j.rootLogger=info 表示log的级别为info,即info级别以上的日志才记录,输出到stdout和D两个Appender
其中D的级别为warn,即只有大于等于warn的日志才记录的真实的log文件中。
Java代码用法: private Log log = LogFactory.getLog(masterController.class); 
命名空间:
1 import org.apache.commons.logging.Log;
2 import org.apache.commons.logging.LogFactory;

 

log4j 简单用法