Enable JSON logging on Spring Boot

Enable JSON logging on Spring Boot

Many log management solutions require services to produce JSON formatted logs. That is particularly useful to run some analytics and create charts based on the generated logs. Unfortunately, Spring Boot does not support JSON logging out of the box. But it is pretty simple to achieve that. In this article, we discuss how to enable JSON logging on Spring Boot applications.

Using Logback

There are many ways to enable JSON logging on Spring Boot applications. But all of them require adding a logging library. Some are better than others. Some are complicated to configure, etc. The easiest library to configure that also plays very nicely with Spring is Logback.

So we are going to use Logback here and create a separate Spring profile for JSON logging exclusively. That gives enough flexibility to enable or disable the JSON logging when it’s necessary. For that, we do a simple configuration to instruct the Logback to produce JSON logs on a profile activation.

First, add Logback dependencies to the project as follows (Maven project):

Then configure the Logback by creating thelogback-spring.xml file under /src/main/resource directory with the following content,

In the above file, we defined a Spring profile called json-logging. So whenever the profile is active, it outputs JSON formatted logs. Otherwise, it uses the console appender log that produces normal logs.

To activate the json-loggin profile, run your Maven project as follows:

Afterward, JSON logging should be enabled on your Spring Boot application.

For more Spring tutorials, check the Spring category.

Inline/featured images credits