[JAVA] Output Spring Boot log in json format

reference

JSON Logging for Spring Boot After that, the contents implemented according to the above article are posted. The above article has more information, so if you are not comfortable with English, we recommend that you refer to it.

Execution environment

Preparation

Added logstash to dependencies

build.gradle


dependencies {
	implementation 'net.logstash.logback:logstash-logback-encoder:6.1'
}

Added logback settings

src/main/resources/logback-spring.xml


<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <property resource="application.yml" />
    <contextName>${spring.application.name}</contextName>
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
            <providers>
                <timestamp>
                    <fieldName>timeStamp</fieldName>
                    <timeZone>UTC</timeZone>
                </timestamp>
                <loggerName>
                    <fieldName>logger</fieldName>
                </loggerName>
                <logLevel>
                    <fieldName>level</fieldName>
                </logLevel>
                <threadName>
                    <fieldName>thread</fieldName>
                </threadName>
                <mdc />
                <message>
                    <fieldName>message</fieldName>
                </message>
                <arguments>
                    <includeNonStructuredArguments>false</includeNonStructuredArguments>
                </arguments>
                <stackTrace>
                    <fieldName>stack</fieldName>
                </stackTrace>
            </providers>
        </encoder>
    </appender>
    <root level="INFO">
        <appender-ref ref="CONSOLE" />
    </root>
</configuration>

Implementation

Example of outputting INFO log in Controller class

TestController.java


package com.exsample.controller;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static net.logstash.logback.argument.StructuredArguments.v;

@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {
    @GetMapping
    public void get() {
        MDC.put("MDC key","MDC value");
        log.info("JSON Log",v("arg key","arg value"));
    }
}

result

The following log is output

{"timeStamp":"2019-08-28T08:52:22.173Z","logger":"com.exsample.controller.TestController","level":"INFO","thread":"main","MDC key":"MDC value","message":"JSON Log","arg key":"arg value"}

Supplement

(Excerpt) logback-spring.xml


<providers>
  <timestamp>
    <fieldName>timeStamp</fieldName>
    <timeZone>UTC</timeZone>
  </timestamp>
  <loggerName>
    <fieldName>logger</fieldName>
  </loggerName>
  <logLevel>
    <fieldName>level</fieldName>
  </logLevel>
  <threadName>
    <fieldName>thread</fieldName>
  </threadName>
  <mdc />
  <message>
    <fieldName>message</fieldName>
  </message>
  <arguments>
    <includeNonStructuredArguments>false</includeNonStructuredArguments>
  </arguments>
  <stackTrace>
    <fieldName>stack</fieldName>
  </stackTrace>
</providers>

Log contents


{
  "timeStamp": "2019-08-28T08:52:22.173Z",
  "logger": "com.exsample.controller.TestController",
  "level": "INFO",
  "thread": "main",
  "MDC key": "MDC value",
  "message": "JSON Log",
  "arg key": "arg value"
}

(Excerpt) TestController.java


MDC.put("MDC key","MDC value");

Log excerpt


"MDC key": "MDC value"

(Excerpt) TestController.java


log.info("JSON Log",v("arg key","arg value"));

Log excerpt


"message": "JSON Log"

(Excerpt) TestController.java


log.info("JSON Log",v("arg key","arg value"));

Log excerpt


"arg key": "arg value"

Recommended Posts

Output Spring Boot log in json format
Output request and response log in Spring Boot
Log output in Json format using lograge / lograge-sql with RubyOnRails
File output bean as JSON in spring
Format of the log output by Tomcat itself in Tomcat 8
Set context-param in Spring Boot
Spring Boot 2 multi-project in Gradle
Major changes in Spring Boot 1.5
NoHttpResponseException in Spring Boot + WireMock
Output embedded Tomcat access log to standard output with Spring Boot
Authenticate 3 or more parameters in JSON format using Spring Security
Spring Boot Hello World in Eclipse
Write test code in Spring Boot
Log output to file in Java
Implement REST API in Spring Boot
What is @Autowired in Spring boot?
Implement Spring Boot application in Gradle
Spring Data JPA SQL log output
Thymeleaf usage notes in Spring Boot
Output system log by Spring AOP technology
Launch (old) Spring Boot project in IntelliJ
Build Spring Boot + Docker image in Gradle
Static file access priority in Spring boot
Local file download memorandum in Spring Boot
Try using JSON format API in Java
Create Java Spring Boot project in IntelliJ
Loosen Thymeleaf syntax checking in Spring Boot
Output Date in Java in ISO 8601 extended format
[Practice! ] Display Hello World in Spring Boot
Use DynamoDB query method in Spring Boot
DI SessionScope Bean in Spring Boot 2 Filter
Change session timeout time in Spring Boot
SameSite cookie in Spring Boot (Spring Web MVC + Tomcat)
Spring Boot Whitelabel Error Page and JSON Response
Test controller with Mock MVC in Spring Boot
Asynchronous processing with regular execution in Spring Boot
Run a Spring Boot project in VS Code
Prepare for log output using log4j in Eclipse.
Challenge Spring Boot
Use Servlet filter in Spring Boot [Spring Boot 1.x, 2.x compatible]
How to add a classpath in Spring Boot
Request parameter log output sample Java & Spring MVC
Java tips-Create a Spring Boot project in Gradle
Spring Boot Form
How to bind to property file in Spring Boot
Spring Boot Memorandum
gae + spring boot
Annotations used in Spring Boot task management tool
View the Gradle task in the Spring Boot project
Specify the encoding of static resources in Spring Boot
Include external jar in package with Spring boot2 + Maven3
I checked asynchronous execution of queries in Spring Boot 1.5.9
[Rails] Return login result in JSON format (for beginners)
How to create a Spring Boot project in IntelliJ
SSO with GitHub OAuth in Spring Boot 1.5.x environment
How to use CommandLineRunner in Spring Batch of Spring Boot
Test field-injected class in Spring boot test without using Spring container
Until you start development with Spring Boot in eclipse 1
Try gRPC in Spring Boot & Spring Cloud project (Mac OS)
Introduce swagger-ui to REST API implemented in Spring Boot
Until you start development with Spring Boot in eclipse 2