⭐⭐⭐ Spring Boot 项目实战 ⭐⭐⭐ Spring Cloud 项目实战
《Dubbo 实现原理与源码解析 —— 精品合集》 《Netty 实现原理与源码解析 —— 精品合集》
《Spring 实现原理与源码解析 —— 精品合集》 《MyBatis 实现原理与源码解析 —— 精品合集》
《Spring MVC 实现原理与源码解析 —— 精品合集》 《数据库实体设计合集》
《Spring Boot 实现原理与源码解析 —— 精品合集》 《Java 面试题 + Java 学习指南》

摘要: 原创出处 juejin.cn/post/7447872749756989440 「考虑考虑」欢迎转载,保留摘要,谢谢!


🙂🙂🙂关注微信公众号:【芋道源码】有福利:

  1. RocketMQ / MyCAT / Sharding-JDBC 所有源码分析文章列表
  2. RocketMQ / MyCAT / Sharding-JDBC 中文注释源码 GitHub 地址
  3. 您对于源码的疑问每条留言都将得到认真回复。甚至不知道如何读源码也可以请教噢。
  4. 新的源码解析文章实时收到通知。每周更新一篇左右。
  5. 认真的源码交流微信群。

前言

日志排查,是系统故障排除必不可少的重要环节,Springboot3.4.0版本发布之后,支持日志结构化,它支持Elastic Common Schema (ECS)和Logstash格式,但也可以使用自己需要的日志格式进行扩展

日志结构化

ecs控制台打印

一般情况下,Springboot打印日志是以下格式

在application.properties配置

logging.structured.format.console=ecs

日志在控制台输出是以下格式

结构化日志写到文件

Springboot3.4.0版本支持将结构化日志写到日志文件里面去,在application.properties配置

logging.structured.format.file=ecs
logging.file.name=./demo-log.log

会有日志文件生成

文件内容为

自定义日志结构化

Springboot3.4.x版本提供了StructuredLogFormatter接口自定义日志格式化

只有Springboot3.4.0才支持

定义一个日志类

package cn.com.ut.cloud.demolog.config;

import ch.qos.logback.classic.spi.ILoggingEvent;
import org.springframework.boot.logging.structured.StructuredLogFormatter;

public class MyStructuredLoggingFormatter implements StructuredLogFormatter<ILoggingEvent> {

@Override
public String format(ILoggingEvent event) {
return "time=" + event.getTimeStamp() + ",level=" + event.getLevel() + ",message=" + event.getMessage() + "\n";
}

}

然后再application-properties配置

logging.structured.format.console=cn.com.ut.cloud.demolog.config.MyStructuredLoggingFormatter

这个时候,日志会按我们需要的进行打印

日志结构化配置

Springboot3.4.x版本支持以下配置

logging.structured.ecs.service.name=MyApp
logging.structured.ecs.service.version=1
logging.structured.ecs.service.environment=Production
logging.structured.ecs.service.node-name=Primary

会在日志打印输出

而且支持MDC打印

package cn.com.ut.cloud.demolog.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
class MyLogger implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(MyLogger.class);

@Override
public void run(String... args) {
MDC.put("userId", UUID.randomUUID().toString());
logger.info("hello world==================");
MDC.remove("userId");
}
}

会有id打印

总结

结构化日志可以帮助在开发过程中,更好的定义日志输出等,至于需不需要,就各自系统开发需求

文章目录
  1. 1. 前言
  2. 2. 日志结构化
    1. 2.1. ecs控制台打印
    2. 2.2. 结构化日志写到文件
    3. 2.3. 自定义日志结构化
    4. 2.4. 日志结构化配置
  3. 3. 总结