How to setup Logging in Spring Boot
Implement Logback in Spring Boot
Spring Boot comes with build-in logging functionality and its very easy to integrate.
Logback
Spring Boot uses logback
logging framework. Logback
in an upgrade of log4j framework.
It comes bundled with spring boot starter packs.
For example if we using spring web service, then logback
comes bundled with it.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services<actifactId>
</dependency>
Implementation
To use logging in a Java class use below code
Logger logger = LoggerFactory.getLogger(getClass());
logger.error("This is an error");
That’s it !! just two lines. Spring boot makes it that easy !
Log Levels
There are different log levels that we can use with Spring Boot. These are shown below,
logger.trace("This is a trace");
logger.debug("This is a debug");
logger.info("This is info");
logger.warn("This is a warn");
logger.error("This is a error");
Logback configuration
Logback
has many configurations. These can be set in application.yml
as shown below,
logging:
file:
name:C:/logfolder/logfile.log
pattern:
file: '%date{dd MMM yyyy - HH:mm:ss.SSS}'
level:
com.example.www:DEBUG
Configurations are set under logging
tag in application.yml
.
- The location of the log file and where it will be saved is defined in
name
tag. - The pattern is defined in
pattern
tag. This defines how the log file will be printed. - And
level
tag indicates from which level the logs will be printed.
In the above example since we have declared DEBUG
; debug, info, warn and error logs will be printed.
If we had declared TRACE
, then logs marked trace, ,debug, info, warn and error logs would be printed.
There are many other configurations, that can be done to Spring Boot logging. More information can be found here.
That’s how we can implement logging in Spring Boot. For more articles on Java click here.