Log4j2+Slf4j快速入门

时间:2022-07-25 21:49:29

前言

        本文目的在于让RD快速掌握Log4j2+Slf4j在Java Web项目中的使用。

        注意:该方法对Servlet3.0+适用,Servlet2.5以前的版本还需额外的步骤,详见:Servlet-2.5

Maven依赖

<dependency>
     <groupId>org.apache.logging.log4j</groupId>
     <artifactId>log4j-api</artifactId>
     <version> 2.5 </version>
</dependency>
<dependency>
     <groupId>org.apache.logging.log4j</groupId>
     <artifactId>log4j-core</artifactId>
     <version> 2.5 </version>
</dependency>
<dependency>
     <groupId>org.apache.logging.log4j</groupId>
     <artifactId>log4j-web</artifactId>
     <version> 2.5 </version>
     <scope>runtime</scope>
</dependency>
<dependency>
     <groupId>org.slf4j</groupId>
     <artifactId>slf4j-api</artifactId>
     <version> 1.7 . 13 </version>
</dependency>
<dependency>
     <groupId>org.apache.logging.log4j</groupId>
     <artifactId>log4j-slf4j-impl</artifactId>
     <version> 2.5 </version>
</dependency>

配置文件

注意:配置文件置于项目的classpath路径下,命名为“log4j2.xml”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<? xml  version = "1.0"  encoding = "UTF-8" ?>
< Configuration  status = "WARN"  monitorInterval = "60" >
     < Appenders >
         < Console  name = "Console"  target = "SYSTEM_OUT" <!-- 定义类型为Console的Appender -->
             < PatternLayout  pattern = "%d{HH:mm:ss.SSS} [%level] %c{1} - %msg%n" />  <!-- 定义类型为Pattern的Layout -->
         </ Console >
     </ Appenders >
     < Loggers >
         < Root  level = "error" <!-- 定义Root Logger,其日志级别为error -->
             < AppenderRef  ref = "Console" />  <!-- Root Logger的Appender引用上面定义的Console -->
         </ Root >
         < Logger  name = "HelloWorld"  level = "info"  additivity = "false" <!-- 定义名字为HelloWorld的Logger,其日志级别为info,additivity为false -->
             < AppenderRef  ref = "Console" />  <!-- Root Logger的Appender引用上面定义的Console -->
         </ Logger >
     </ Loggers >
</ Configuration >

打印日志

1
2
3
4
5
6
7
8
9
10
import  org.slf4j.Logger;
import  org.slf4j.LoggerFactory;
  
public  class  MyClass {
     /* 获取名字为HelloWorld的Logger,若无该Logger,则根据继承结构向父节点寻找,直到找到Root Logger为止 */
     private  static  final  Logger HELLO_LOGGER = LoggerFactory.getLogger( "HelloWorld" ); 
     public  void  method() {
         HELLO_LOGGER.info( "Hello World!" );  // 打印日志信息
     }
}