JDK Logging in Spring Boot Applications

 

When writing spring boot applications, it is recommended to use SLF4J API for logging. However it is also possible to use the logging implementation provided by JDK directly. However JDK logging implementation (JUL) provides a different set of logging levels compared to SLF4J or Log4J. The logging levels used by JDK library are,

FINEST > FINER > FINE > CONFIG > INFO > WARNING > SEVERE

SLF4J and other logging implementations such as Log4j use the following log levels,

ALL > TRACE > DEBUG > INFO > WARN > ERROR > FATAL > OFF

Spring boot’s SLF4J bridge maps the log levels to the JDK logging levels using the following table.

1 FINEST  => TRACE
2 FINER   => DEBUG
3 FINE    => DEBUG
4 CONFIG  => INFO
5 INFO    => INFO
6 WARNING => WARN
7 SEVERE  => ERROR

Spring boot propagates the logging configuration set in application.properties to JDK logging classes as well. Hence even if you are using both logging libraries in your application (JDK logging and Logback with SLF4J), the same set of configuration in application.properties can be used! For example, the following configuration sets the root logger to WARN (WARNING) level and all application classes to TRACE (FINEST). Note that you need to use the log levels defined by SLF4J.

1 # application.properties values
2 logging.level.root=WARN
3 logging.level.com.quickprogrammingtips=TRACE

To configure only the logback system, create a custom logback.xml or logback-spring.xml. To configure only the JDK logging classes (JUL), create a custom logging.properties file. These files should be created in src/main/resources folder.

Using JDK Logging (JUL) in Spring Boot Classes

Here is a simple spring boot controller which uses the JDK logging library,

1 package com.quickprogrammingtips.springboot;
2  
3 import java.util.logging.Logger;
4  
5 import org.springframework.stereotype.Controller;
6 import org.springframework.web.bind.annotation.RequestMapping;
7 import org.springframework.web.bind.annotation.ResponseBody;
8  
9 @Controller
10 public class HelloWorld2Controller {
11     private static final Logger LOG = Logger.getLogger(HelloWorld2Controller.class.getName());
12  
13     @RequestMapping("/hello2")
14     @ResponseBody
15     String home() {
16         LOG.finest("Sending hello world message!");
17         return "Hello World!";
18     }
19 }

 

USEFUL RESOURCES:

Spring training in chennai

spring official