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 spring-boot-starter-web dependency of which is below. 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 that 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
Output to File
If you want log messages to be stored in a log file as well you can provide a path to a file where logging messages should be stored in an application.properties file. Add the following property to application.properties file to output logging to a 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 be able to quickly add 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.