Spring Boot Logging using Logback

Spring Boot Logging using Logback

In this article, I am going to discuss Spring Boot Logging using Logback. Please read our previous article where we discussed Spring Boot Logging.

Spring Boot Logging using Logback

Spring Boot uses Apache Commons Logging by default. In this article, we will learn how to modify the default setting to use Logback. Logback is logging software that stores logs in .xml format.

Step 1: Create a new file called logback.xml in the src/main/java/com/dotnet/demo folder.

Step 2: Add the following lines to the logback.xml file just created:

Spring Boot Logging using Logback

Following parameters are set for logging

  • The first appender is for the console output. Hence the name of this appender is STDOUT.
  • The second appender is for the file output. Hence the name of this appender is FILE.
  • The root section sets the root logging type.

Step 3: Modify the DemoApplication.java file to send some log messages. Also import required libraries:

Spring Boot Logging using Logback

The following modifications are done:

  • On lines 9 and 10, two new packages have been imported. This helps us to create an object of type Logger, which can be used to send log messages.
  • On line 17, an object of the type Logger is created. This can be done using the LoggerFactory.getLogger() function. Note that the object is set to be private and final. This means that this object cannot be accessed outside of the DemoApplication class and that the object cannot be modified.
  • From lines 21 to 23, three lines have been added that print some message to the log. this comprises one INFO, one WARN, and one ERROR.

Step 4: Execute the application to see the log.

Spring Boot Logging using Logback

As can be seen in the screenshot, the log output follows the format specified in the logback.xml file. Also, the other information, such as the thread name, type of log, and message has been printed correctly. This feature can be used to print custom logs as per requirement.

In the next article, I am going to discuss Spring Boot RESTful Web Services with Examples. Here, in this article, I try to explain Spring Boot Logging using Logback. I hope you enjoy this Spring Boot Logging using Logback article.

Leave a Reply

Your email address will not be published. Required fields are marked *