Warm tip: This article is reproduced from serverfault.com, please click

java-如何使用logback以文本和json格式打印Spring Boot日志?

(java - How to print Spring Boot log in both text and json format using logback?)

发布于 2020-11-29 13:06:09

对于日志记录,我们使用Logback。当前,我们正在使用Splunk查看Spring Boot日志。根据项目要求,我们需要转向Kibana。首先,我们应该以JSON格式登录,以便Kibana可以轻松对其进行处理。目前,我们并没有用Kibana替代Splunk,但是当与Kibana的集成成功后,我们便可以逐步在所有项目中替代Splunk。

因此,根据要求,我们需要现有的日志,即文本日志,但出于研发目的,我们还需要JSON日志。

Questioner
Johny Johnson
Viewed
11
Altaf Java 2020-11-29 21:15:14

这很简单。你只需要logstash-logback-encoderpom.xml文件中添加依赖项并在文件中编写一些配置即可logback.xml请按照以下步骤操作,以满足你的要求。

步骤1:在中添加logstash-logback-encoder依赖项pom.xml

<dependency>
    <groupId>net.logstash.logback</groupId>
    <artifactId>logstash-logback-encoder</artifactId>
    <version>6.4</version>
</dependency>

步骤2:在其中创建logback.xml文件,src/main/resources/然后将以下内容复制粘贴。

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
  <include resource="org/springframework/boot/logging/logback/defaults.xml" />
  <include resource="org/springframework/boot/logging/logback/console-appender.xml" />
  <property name="LOG_PATH" value="logs" />
  <property name="CONSOLE_LOG_PATTERN" value="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %X{id} %c{1} - %msg%n" />
  <property name="FILE_LOG_PATTERN" value="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %X{id} %c{1} - %msg%n" />

  <appender name="CONSOLE_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>${CONSOLE_LOG_PATTERN}</pattern>
      <charset>utf8</charset>
    </encoder>
  </appender>

  <appender name="ROLLING_TEXT_FILE_APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_PATH}/application-text.log</file>
    <encoder>
      <Pattern>${FILE_LOG_PATTERN}</Pattern>
    </encoder>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <fileNamePattern>${LOG_PATH}/application-text.%d{yyyy-MM-dd}.%i.gz
      </fileNamePattern>
      <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
        <maxFileSize>100MB</maxFileSize>
      </timeBasedFileNamingAndTriggeringPolicy>
      <maxHistory>10</maxHistory>
    </rollingPolicy>
  </appender>
  
  <appender name="ROLLING_JSON_FILE_APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${LOG_PATH}/application-json.log</file>
    <encoder class="net.logstash.logback.encoder.LogstashEncoder" />
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <fileNamePattern>${LOG_PATH}/application-json.%d{yyyy-MM-dd}.%i.gz
      </fileNamePattern>
      <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
        <maxFileSize>100MB</maxFileSize>
      </timeBasedFileNamingAndTriggeringPolicy>
      <maxHistory>10</maxHistory>
    </rollingPolicy>
  </appender>

  <root level="INFO">
    <appender-ref ref="CONSOLE_APPENDER" />
    <appender-ref ref="ROLLING_TEXT_FILE_APPENDER" />
    <appender-ref ref="ROLLING_JSON_FILE_APPENDER" />
  </root>
</configuration>

步骤3:现在你可以在类中的任何位置使用log语句。假设你在Spring Boot的主类中使用。

import org.slf4j.MDC;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.altafjava.constant.AppConstant;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@SpringBootApplication
public class JsonLogApplication {

    public static void main(String[] args) {
        SpringApplication.run(JsonLogApplication.class, args);
        MDC.put("id", AppConstant.PROJECT_NAME_PREFIX + "_" + AppConstant.MARKET_CODE + "_" + AppConstant.PARAM_TYPE);
        log.info("---------- Spring Application started successfully ----------");
        log.debug("This is a debug message.");
        log.info("This is an info message.");
        log.warn("This is a warn message.");
        log.error("This is an error message.");
        log.info("---------- Spring Application ended successfully ----------");
    }
}

这将在logs目录内创建两个日志文件

  1. application-text.log 看起来像这样
[INFO ] 2020-09-11 22:36:13.627 [main] DEMO_IND_PARAM c.a.JsonLogApplication - ---------- Spring Application started successfully ----------
[INFO ] 2020-09-11 22:36:13.630 [main] DEMO_IND_PARAM c.a.JsonLogApplication - This is an info message.
[WARN ] 2020-09-11 22:36:13.630 [main] DEMO_IND_PARAM c.a.JsonLogApplication - This is a warn message.
[ERROR] 2020-09-11 22:36:13.631 [main] DEMO_IND_PARAM c.a.JsonLogApplication - This is an error message.
[INFO ] 2020-09-11 22:36:13.631 [main] DEMO_IND_PARAM c.a.JsonLogApplication - ---------- Spring Application ended successfully ----------
  1. application-json.log 看起来像这样
{"@timestamp":"2020-09-11T22:36:13.627+05:30","@version":"1","message":"---------- Spring Application started successfully ----------","logger_name":"com.altafjava.JsonLogApplication","thread_name":"main","level":"INFO","level_value":20000,"id":"DEMO_IND_PARAM"}
{"@timestamp":"2020-09-11T22:36:13.630+05:30","@version":"1","message":"This is an info message.","logger_name":"com.altafjava.JsonLogApplication","thread_name":"main","level":"INFO","level_value":20000,"id":"DEMO_IND_PARAM"}
{"@timestamp":"2020-09-11T22:36:13.630+05:30","@version":"1","message":"This is a warn message.","logger_name":"com.altafjava.JsonLogApplication","thread_name":"main","level":"WARN","level_value":30000,"id":"DEMO_IND_PARAM"}
{"@timestamp":"2020-09-11T22:36:13.631+05:30","@version":"1","message":"This is an error message.","logger_name":"com.altafjava.JsonLogApplication","thread_name":"main","level":"ERROR","level_value":40000,"id":"DEMO_IND_PARAM"}
{"@timestamp":"2020-09-11T22:36:13.631+05:30","@version":"1","message":"---------- Spring Application ended successfully ----------","logger_name":"com.altafjava.JsonLogApplication","thread_name":"main","level":"INFO","level_value":20000,"id":"DEMO_IND_PARAM"}

注意:这里@ Slf4j是Lombok批注。这意味着无需创建LoggerFactory,你就可以直接使用日志方法。你需要在IDE中安装Lombok并在pom.xml中添加依赖项

如果你需要演示项目,请访问https://github.com/altafjava/json-log