Spring Boot Logging with LoggerFactory

Adding logging support to your RESTful Web Service application with Spring Boot is extremely simple.

To use Spring Boot logging, you do not need to add any additional dependencies or libraries to your web app project other than the spring-boot-starter-web dependency. If you are working on a Spring Boot Web or a Web Services project, you likely already have the below dependency in your pom.xml file. Otherwise, you need to add it.


Adding Logging to Your Java Class

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

To make logging work for this rest controller class, 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;

public class UsersController {

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

Enable DEBUG level logging

To enable DEBUG level logging for all classes in a Java package, you can update application.properties. An example of how to update the application.properties file is below.


You can also switch the logging levels for your application at runtime.

Output logs to a File

Log messages can be stored in a log file. To configure your Spring Boot application to output log messages to a specific file, add the following property to the application.properties file.

logging.file = /complete-path-to-file-here/log-file-name.log

And this is it!

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

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

Leave a Reply

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