Search code examples
spring-bootlogginglog4j2logbackgelf

Logging with JSON GELF format in Spring Boot


I'm using Spring Boot and would like to have this code:

LOG.info("Scheduled appointment for user 12345 [appointment ID 100]");

Produce the following log message in JSON GELF format:

{
  "version": "1.1",
  "host": "hostname.ec2.internal",
  "short_message": "Scheduled appointment for user 12345 [appointment ID 100]",
  "timestamp": 1318280136,
  "level": 1,
  "_user": "[email protected]",
  "_clientip": "127.0.0.1",
  "_env": "prod",
  "_app":"scheduler"
}

Do I need to create my own logger for this or can I customize Logback/Log4j2 to behave this way?


Solution

  • From a Log4j 2.x perspective, you can use the JSON Layout Template, which has a built-in eventTemplate for GELF.

    Your appender configuration in the log4j2-spring.xml file would look like:

    <Console name="CONSOLE">
        <JsonTemplateLayout eventTemplateUri="classpath:GelfLayout.json" />
    </Console>
    

    Remark: Since Spring Boot uses Logback as default logging system, you'll have to exclude the spring-boot-starter-logging and replace it with spring-boot-starter-log4j2.

    Moreover the JSON Layout Template requires an additional dependency:

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-layout-template-json</artifactId>
    </dependency>