解锁可观察性:Spring Boot 中的结构化日志记录
In this section we describe how to add structured logs using SLF4J (or Simple Logging Facade for Java). There are three main components that we need to configure:
在本节中,我们将介绍如何使用SLF4J(或Java的简单日志门面)添加结构化日志。我们需要配置三个主要组件:
- Log format: By default an application will produce logs in a text format — we have to add structure to these logs by defining a format. In this blog, we will use a structured JSON format.
- 日志格式:默认情况下,应用程序会以文本格式生成日志,我们需要通过定义格式来为这些日志添加结构。在本博客中,我们将使用结构化的JSON格式。
- Log generation: We need to configure our application to include contextual information in addition to the log message, like a user-id who made a request.
- 日志生成:我们需要配置应用程序以包含上下文信息,除了日志消息之外,还包括发出请求的用户ID等。
- Log ingestion: Ultimately we have to ingest these logs into a data store that allows us to interact with the logs. We will use logstash to push application logs into our storage engine Elasticsearch and we will use Kibana as the logging UI.
- 日志摄取:最终我们需要将这些日志摄取到一个允许我们与日志交互的数据存储中。我们将使用logstash将应用程序日志推送到我们的存储引擎Elasticsearch,并使用Kibana作为日志界面。
Step 1: Generating logs
第一步:生成日志
In our demo application, we choose to use SLF4J with Logback, which is a commonly used logging framework. This is defined in the project dependencies.
在我们的演示应用程序中,我们选择使用 SLF4J 和 Logback,这是一个常用的日志框架。这在 项目依赖项 中定义。
SLF4J is a logging facade that works with many logging backends, in this article, we demonstrate structured logging with SLF4J and Logback as a backend
SLF4J是一个与许多日志后端一起使用的日志门面,本文中,我们演示了SLF4J和Logback作为后端的结构化日志记录
Adding logs is a two-step process:
添加日志是一个两步过程:
public class PartyController {
private final Logger logger = LoggerFactory.getLogger(getClass().getName());
public class PartyController {
private final Logger logger = LoggerFactory.getLogger(getClass().getName());
public Map<String, String> index() {
public Map<String, String> index() {
logger.info("Reading index path");
return Map.of("message", "Welcome to Jamboree!"); }
logger.info("读取索引路径");
return Map.of("message", "欢迎来到Jamboree!"); }
}
}
This will generate logs in a text-only format. To add a structure to the logs...