spring boot log4j2 最佳实践
- 2021 年 10 月 17 日
- 筆記
- JAVA, log4j2, Spring Boot, 最佳实践
为什么选择 log4j2
Log4j2 使用了 LMAX Disruptor 库。在多线程场景中,异步 Logger 的吞吐量比 Log4j 1.x 和 Logback 高 18 倍,延迟低几个数量级。如下是官网的性能对比:
上图来源://logging.apache.org/log4j/2.x/performance.html
最终效果
- 日志输出整齐有序;
- 不同级别日志采用不同颜色输出,更加清晰直观;
- 日志输出可带有用户标识或特定标识,有利于查看同组的多个请求轨迹、排查问题;
- 不同环境采用不同配置,本地测试日志只输出到控制台,其他环境日志输出到指定文件;
- 线上日志按天分割,历史日志按月压缩存放,定期删除之前日志,便于排查问题,防止日志累积达到磁盘上限;
- 警告错误日志再单独输出到错误日志文件中,便于快速定位问题;
日志效果图
代码示例
maven 依赖
点击查看代码
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</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>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
注入标识过滤器
点击查看代码
import org.slf4j.MDC;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class UidLogFilter extends OncePerRequestFilter {
private static final String UID = "Uid";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String uid = request.getHeader(UID);
if (!StringUtils.hasLength(uid)){
uid = request.getParameter(UID);
}
/**
* 将用户标识放入日志上下文中
*/
MDC.put("uid", uid);
filterChain.doFilter(request, response);
}
}
BestPracticeApplication
点击查看代码
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@SpringBootApplication
public class BestPracticeApplication {
/**
* 根据请求参数输出不同级别的日志
*/
@GetMapping("/")
public String home(String level) {
String msg = "Hello World!";
try {
switch (level){
case "trace": log.trace(msg); break;
case "debug": log.debug(msg); break;
case "info": log.info(msg); break;
case "warn": log.warn(msg); break;
case "error": log.error(msg); break;
//带参数的日志输出方式
default: log.error("未知的日志级别: {}", level); break;
}
}catch (NullPointerException e){
//异常日志输出方式
log.error("日志级别为空", e);
}
return msg;
}
@Bean
public UidLogFilter uidLogFilter(){
return new UidLogFilter();
}
static {
System.setProperty("log4j.skipJansi", "false");
}
public static void main(String[] args) {
SpringApplication.run(BestPracticeApplication.class, args);
}
}
application.yml
点击查看代码
spring:
profiles:
active: local
---
#本地环境
spring:
config:
name: local
logging:
config: classpath:log4j2-local.xml
---
#测试环境
spring:
config:
name: test
---
#线上环境
spring:
config:
name: online
log4j2-local.xml
点击查看代码
<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorInterval="30">
<Properties>
<Property name="LOG_PATTERN_LAYOUT">%d{HH:mm:ss,SSS} %highlight{[%-5.5level]}{STYLE=Logback} [%-5.5thread] %blue{[%-5.5X{uid}]} %cyan{[%-40.40c{1.}:%-4line]} - %msg%xEx%n</Property>
<Property name="DEFAULT_CHARSET">UTF-8</Property>
</Properties>
<Appenders>
<!-- 定义控制台输出 -->
<Console name="Console" target="SYSTEM_OUT" follow="true">
<PatternLayout charset="${DEFAULT_CHARSET}" pattern="${LOG_PATTERN_LAYOUT}"/>
</Console>
</Appenders>
<Loggers>
<!-- 包名以cn.learncoding 开头的日志输出级别为TRACE -->
<Logger name="cn.learncoding" level="TRACE"/>
<!-- 默认日志输出级别为INFO -->
<Root level="INFO">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
log4j2.xml
点击查看代码
<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorInterval="30">
<Properties>
<!-- ${sys:catalina.home:-.}/logs 表示 取系统变量catalina.home指向的目录下面的logs目录,如果没有则取当前所在目录下面的logs目录 -->
<Property name="LOG_HOME">${sys:catalina.home:-.}/logs</Property>
<Property name="LOG_BACK_HOME">${sys:catalina.home:-.}/logs/backup</Property>
<!-- 日志输出格式 -->
<!-- %-5.5thread 表示最少长度为5,不足空格补齐,超出5则只保留后5位 -->
<!-- %highlight{[%-5.5level]}{STYLE=Logback} 表示此字段使用Logback格式的高亮颜色展示,最少长度为5,不足空格补齐,超出5则只保留后5位 -->
<!-- %blue{[%-5.5X{uid}]} 表示此上下文字段采用蓝色进行输出,最少长度为5,不足空格补齐,超出5则只保留后5位 -->
<Property name="LOG_PATTERN_LAYOUT">%d{HH:mm:ss,SSS} %highlight{[%-5.5level]}{STYLE=Logback} [%-5.5thread] %blue{[%-5.5X{uid}]} %cyan{[%-40.40c{1.}:%-4line]} - %msg%xEx%n </Property>
<Property name="DEFAULT_CHARSET">UTF-8</Property>
<Property name="ERROR_FILE_NAME">error</Property>
<Property name="INFO_FILE_NAME">info</Property>
</Properties>
<Appenders>
<!-- 配置日常日志 历史日志按月存放,按天分割压缩存储-->
<RollingFile name="${INFO_FILE_NAME}" fileName="${LOG_HOME}/${INFO_FILE_NAME}.log" filePattern="${LOG_BACK_HOME}/$${date:yyyy-MM}/${INFO_FILE_NAME}-%d{yyyy-MM-dd}.log.gz" append="true">
<PatternLayout charset="${DEFAULT_CHARSET}" pattern="${LOG_PATTERN_LAYOUT}"/>
<Policies>
<!-- 基于时间的滚动策略,按天分割 -->
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
</Policies>
<DefaultRolloverStrategy >
<!--删除30天前的日志-->
<Delete basePath="${LOG_BACK_HOME}" maxDepth="2">
<IfFileName glob="*/*.log.gz" />
<IfLastModified age="30d" />
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
<!-- 配置错误日志 历史日志按月存放,按天分割压缩存储-->
<RollingFile name="${ERROR_FILE_NAME}" fileName="${LOG_HOME}/${ERROR_FILE_NAME}.log" filePattern="${LOG_BACK_HOME}/$${date:yyyy-MM}/${ERROR_FILE_NAME}-%d{yyyy-MM-dd}.log.gz" append="true">
<PatternLayout charset="${DEFAULT_CHARSET}" pattern="${LOG_PATTERN_LAYOUT}"/>
<Policies>
<!-- 基于时间的滚动策略,按天分割 -->
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
</Policies>
<Filters>
<!--级别大于等于WARN的日志可以写入-->
<ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY"/>
</Filters>
</RollingFile>
</Appenders>
<Loggers>
<!-- 默认日志输出级别为INFO -->
<Root level="INFO">
<AppenderRef ref="${INFO_FILE_NAME}"/>
<AppenderRef ref="${ERROR_FILE_NAME}"/>
</Root>
</Loggers>
</Configuration>