Spring Boot Logging with LoggerFactory

It is extremely simple to add logging support to your RESTful Web Service application with Spring Boot. To use Spring Boot logging you do not really need to add any additional dependencies or libraries to your web app project other than the org.springframework.boot example of which is below. But if you are working on a Spring Boot Web project or a Web Services project then most likely you already do have the below dependency in your pom.xml file.

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
</dependency>

Adding Logging to Your Class

Let’s add logging to our RestController for example. Below is a very simple example of a RestController class which logs a message on the DEBUG level.

To make logging work for this rest controller I needed to:

  • Import org.slf4j.Logger and org.slf4j.LoggerFactory to my class,
  • Get an instance of org.slf4j.Logger by using the LoggerFactory and its static method getLogger().
Logger log = LoggerFactory.getLogger(this.getClass());

Example of Java class that uses Spring Boot Logging

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.appsdeveloperblog.examples.jwt.model.request.CreateUserRequestBody;

@RestController
@RequestMapping("/users")
public class UsersController {

 private final Logger log = LoggerFactory.getLogger(this.getClass());
   
 @GetMapping
 public String checkStatus()
 {
  log.debug("Inside of checkStatus() method ");
  return "working";
 }
 
 @PostMapping
 public String createUser(@RequestBody CreateUserRequestBody createUserRequestBody)
 {
  
  return "user created";
 }
}

Update application.properties file

To enable DEBUG level logging for the below class, I needed to update my application.properties as well. An example of how to update the application.properties file is below.

logging.level.com.appsdeveloperblog.examples=DEBUG

And this is it!

There are many more configuration options for advanced users of Logging but to be able to quickly add a very simple logging to your Spring Boot Web App this is all you needed to do.

I hope this short blog post was helpful. If you are interested to learn more about Spring Boot and how to build RESTful Web Services with Spring framework please check the below video courses.