Elements of Logging Framework
- Logger: It captures the messages.
- Formatter: It formats the messages which are captured by loggers.
- Handler: It prints messages on the console, stores them in a file or sends an email, etc.
Java provides several logging frameworks, some of which are:
- Logback Configuration logging
- Log4j2 Configuration logging
- Logging with Lombok
- @Slf4j and @CommonsLog
Initial Setup
To create a simple Spring Boot project using Spring Initializer, please refer to this article. Let’s define a simple Rest Controller that outputs various levels of log messages.
Java
// Rest Controller to print various log level messages package com.log.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class LogController { // creating a logger Logger logger = LoggerFactory.getLogger(LogController. class ); @RequestMapping ( "/log" ) public String log() { // Logging various log level messages logger.trace( "Log level: TRACE" ); logger.info( "Log level: INFO" ); logger.debug( "Log level: DEBUG" ); logger.error( "Log level: ERROR" ); logger.warn( "Log level: WARN" ); return "Hey! You can check the output in the logs" ; } } |
Now we simply need to run the application and hit http://localhost:8080/log to see the log messages.
Spring Boot – Logging
Logging in Spring Boot plays a vital role in Spring Boot applications for recording information, actions, and events within the app. It is also used for monitoring the performance of an application, understanding the behavior of the application, and recognizing the issues within the application. Spring Boot offers flexible logging capabilities by providing various logging frameworks and also provides ways to manage and configure the logs.
Why to use Spring Boot – Logging?
A good logging infrastructure is necessary for any software project as it not only helps in understanding what’s going on with the application but also to trace any unusual incident or error present in the project. This article covers several ways in which logging can be enabled in a spring boot project through easy and simple configurations. Let’s first do the initial setup to explore each option in more depth.