By default, Spring Boot uses Logback for logging. It is also set up to enable routing from common Java logging libraries like Java Util Logging, Commons Logging, Log4J or SLF4J.
It is safe to use SLF4J which is a simple facade for logging in Java. It removes a hard dependency to a logging framework in our code. Logback and Log4J can be used with SLF4J.
To obtain a logger instance, we call getLogger of the org.slf4j.LoggerFactory. The Method is static, and we can create a constant in our class, e.g., ReadController
private static final Logger LOGGER =
LoggerFactory.getLogger(ReadController.class);
Now we can use info, debug or any of the other logging methods.
By default, our log message is printed on the console. This is not suitable for running an application or microservices later, so we are going to change it to file based logging.
Spring Boot offers two properties to enable logging to file. They can work together too.
The properties are set in application.properties or _application.yml.
Spring Boot provides a way to modify the log level with properties set in the application.properties or _application.yml.
They are prefixed by logging.level, and the value is the log level, one of TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF. To set the log level for the root logger use
logging.level.root=WARN
and if we want classes from the Spring Framework to only report errors
logging.level.org.springframework=ERROR
I included a way in Spring Boot: How To Get Started and Build a Microservice. However, I turned this later into an own module, which you can get here.
TLDR; This module helps you in assigning a unique identifier to a request and passing it along. The identifier is stored in the MDC and can be used in Logback as a user variable in the log pattern.