一、简介
slf4j
是日志接口,logback
和log4j2
是其实现。log4j2
的并发效率优于logback
。
二、SpringBoot中使用log4j2
- 由于
SpringBoot
中默认使用logback
作为其日志框架,因此如果需要替换为log4j2
,需要先将logback
的依赖排除。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
- 在
classpath
下新建log4j2
的配置文件,命名为log4j2-spring.xml
,如需重命名,如log4j2.xml
,需要在application.properties
中指定配置文件的位置
logging.config=classpath:log4j2.xml
- 配置文件如下
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO" monitorInterval="30">
<Properties>
<Property name="APP_NAME">spring-log4j2</Property>
<Property name="LOG_HOME">/var/log</Property>
<Property name="printPattern">%date [%thread] [%X{httpRequestId}] %-5level %logger{50} - %msg%n</Property>
<Property name="outputPattern">%date [%thread] [%X{httpRequestId}] %-5level %logger{80} - %msg%n</Property>
</Properties>
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<ThresholdFilter level="ALL" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout>
<pattern>${printPattern}</pattern>
<charset>UTF-8</charset>
</PatternLayout>
</Console>
<RollingFile name="infoLog" fileName="${LOG_HOME}/${APP_NAME}-info.log" filePattern="${LOG_HOME}/$${date:yyyy-MM-dd}/${APP_NAME}-info.%d{yyyy-MM-dd}.%i.log.zip" immediateFlush="true">
<ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout>
<pattern>${outputPattern}</pattern>
<charset>UTF-8</charset>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
<SizeBasedTriggeringPolicy size="100MB"/>
</Policies>
<DefaultRolloverStrategy max="30" />
</RollingFile>
<RollingFile name="errorLog" fileName="${LOG_HOME}/${APP_NAME}-error.log" filePattern="${LOG_HOME}/${APP_NAME}-error.%d{yyyy-MM-dd}.%i.log.zip" immediateFlush="true">
<ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout>
<pattern>${outputPattern}</pattern>
<charset>UTF-8</charset>
</PatternLayout>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
<SizeBasedTriggeringPolicy size="100MB"/>
<DefaultRolloverStrategy max="30" />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="INFO" >
<appender-ref ref="console"/>
<appender-ref ref="infoLog"/>
<appender-ref ref="errorLog"/>
</Root>
</Loggers>
</Configuration>