Spring Boot Logging Example

By | | Updated : 2022-03-15 | Viewed : 61 times

Spring Boot Logging Example

The current article shows how to set up and use different logging frameworks in Spring Boot Logging.

Logging is very important which will be useful. It is the primary tool that will be useful for managing the entire application in case of any bug fixes required. In this tutorial, we will learn about the log4j and logback logging tools with Spring Boot.

Spring Boot Log4j Setup

Firstly, the logging tool, used in this article, is log4j. Now we will learn first how to set up log4j in Spring Boot.

Maven Dependencies for Log4j

Maven Dependencies for Log4j
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!--To configure the log4j2 in spring boot-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-log4j2</artifactId>
        </dependency>
log4j2.properties
status = warn

appender.console.type = Console
appender.console.name = LogToConsole
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

appender.file.type = File
appender.file.name = LogToFile
appender.file.fileName=logs/SpringBoot-Logs-Example-%d{yyyy-MM-dd}.%i.log
appender.file.layout.type=PatternLayout
appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n

# Rotate log file
appender.rolling.type = RollingFile
appender.rolling.name = LogToRollingFile
appender.rolling.fileName = logs/SpringBoot-Logs-Example-App-Log4j.log
appender.rolling.filePattern = logs/${date:yyyy-MM}/SpringBoot-Logs-Example-App-Log4j-%d{yyyy-MM-dd}-%i.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d %p %C{1.} [%t] %m%n
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=10MB
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = 10

# Log to console and rolling file
logger.app.name = com.docsconsole.tutorials
logger.app.level = debug
logger.app.additivity = false
logger.app.appenderRef.rolling.ref = LogToRollingFile
logger.app.appenderRef.console.ref = LogToConsole

rootLogger.level = info
rootLogger.appenderRef.stdout.ref = LogToConsole

Now we will see one example of how to use these logs in our application.

Spring Boot Log4j Example

Log4j Example In Controller
@RestController
@RequestMapping("/curd-app/api/log4J")
public class ProductsControllerLog4j {
    private static final Logger logger = LogManager.getLogger(ProductsControllerLog4j.class);

    @Autowired
    ProductServiceLog4jImpl productServiceImpl;

    @GetMapping("/testWeb")
    public String testWeb() {
        logger.trace("A TRACE Message @testWeb");
        logger.debug("A DEBUG Message @testWeb");
        logger.info("An INFO Message @testWeb");
        logger.warn("A WARN Message @testWeb");
        logger.error("An ERROR Message @testWeb");
        return "Result: Success";
    }

    @GetMapping("/products")
    public ResponseEntity<?> getAllProducts() {
        return productServiceImpl.getAllProducts();
    }

}
SpringBoot-Logs-Example-App-Log4j.log
2022-03-14 21:08:35,474 INFO o.s.b.StartupInfoLogger [main] Starting SpringBootCurdApplication on AmarSivas with PID 4064 (D:\docsconsole-git-master\springboot-master\Spring-Boot-Logs-Example-App\target\classes started by Bangi in D:\docsconsole-git-master\springboot-master\Spring-Boot-Logs-Example-App)
2022-03-14 21:08:35,501 DEBUG o.s.b.StartupInfoLogger [main] Running with Spring Boot v2.3.6.RELEASE, Spring v5.2.11.RELEASE
2022-03-14 21:08:35,504 INFO o.s.b.SpringApplication [main] No active profile set, falling back to default profiles: default
2022-03-14 21:08:39,683 INFO o.s.b.StartupInfoLogger [main] Started SpringBootCurdApplication in 5.248 seconds (JVM running for 8.146)
2022-03-14 21:09:01,159 DEBUG c.d.t.s.ProductServiceLog4jImpl [http-nio-8080-exec-3] Test debug message
2022-03-14 21:09:09,952 DEBUG c.d.t.c.ProductsControllerLog4j [http-nio-8080-exec-4] A DEBUG Message @testWeb
2022-03-14 21:09:09,953 INFO c.d.t.c.ProductsControllerLog4j [http-nio-8080-exec-4] An INFO Message @testWeb
2022-03-14 21:09:09,954 WARN c.d.t.c.ProductsControllerLog4j [http-nio-8080-exec-4] A WARN Message @testWeb
2022-03-14 21:09:09,955 ERROR c.d.t.c.ProductsControllerLog4j [http-nio-8080-exec-4] An ERROR Message @testWeb

Spring Boot Logback Set Up

Now we will look at logback logging tool. Firstly we will look now at how to set up logback logging tool.

Maven Dependencies for Logback

Maven Dependencies for Logback
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

The parent spring-boot-starter-web library contains other libraries which are below.

Maven dependencies in spring-boot-starter-web Dependencies
<dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jul-to-slf4j</artifactId>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>log4j-over-slf4j</artifactId>
    </dependency>

And we will have to add required properties into application.properties as shown below

application.properties
#################log back configurations######################
logging.path=logs
logging.file.name=${logging.path}/SpringBoot-Logs-Example-App-logback.log   
logging.pattern.rolling-file-name=${logging.path}/${date:yyyy-MM}/SpringBoot-Logs-Example-App-logback-%d{yyyy-MM-dd}.%i.log
#threshold size for log file
logging.file.max-size=1MB
#Threshold size for all the log files
logging.file.total-size-cap=10MB
#Maximum number of days that archived log files are kept
logging.file.max-history=30
#Clean the archived log files on startup
logging.file.clean-history-on-start=true

logging.level.com.docsconsole.tutorials=debug
logging.pattern.file=%d{dd-MM-yyyy HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M - %msg%n
logging.pattern.console=%d{dd-MM-yyyy HH:mm:ss.SSS} %magenta([%thread]) %highlight(%-5level) %logger.%M - %msg%n

Spring Boot Logback Example

Now, we will the above-given setup to log the messages in our Spring Boot application.

ProductsControllerLogback
@RestController
@RequestMapping("/curd-app/api/logback")
public class ProductsControllerLogback {
    Logger logger = LoggerFactory.getLogger(ProductsControllerLogback.class);

    @Autowired
    ProductServicelogBackImpl productServiceImpl;

    @GetMapping("/testWeb")
    public String testWeb() {
        logger.trace("A TRACE Message @testWeb");
        logger.debug("A DEBUG Message @testWeb");
        logger.info("An INFO Message @testWeb");
        logger.warn("A WARN Message @testWeb");
        logger.error("An ERROR Message @testWeb");
        return "Result: Success";
    }

    @GetMapping("/products")
    public ResponseEntity<?> getAllProducts() {
        return productServiceImpl.getAllProducts();
    }

}

And we can write the logs in the service class as we need to track.

ProductServicelogBackImpl.java
@Service
public class ProductServicelogBackImpl {

    Logger logger = LoggerFactory.getLogger(ProductServicelogBackImpl.class);

    public ResponseEntity<?> getAllProducts() {
        //logic to fetch the products

        logger.debug("Test debug message");
        return ResponseEntity.ok(list);
    }
}
SpringBoot-Logs-Example-App-logback.log
15-03-2022 18:47:57.717 [main] INFO  c.d.t.SpringBootCurdApplication.logStarting - Starting SpringBootCurdApplication on AmarSivas with PID 3300 (D:\docsconsole-git-master\springboot-master\Spring-Boot-Logs-Example-App\target\classes started by Bangi in D:\docsconsole-git-master\springboot-master\Spring-Boot-Logs-Example-App)
15-03-2022 18:47:57.764 [main] DEBUG c.d.t.SpringBootCurdApplication.logStarting - Running with Spring Boot v2.3.6.RELEASE, Spring v5.2.11.RELEASE
15-03-2022 18:47:57.764 [main] INFO  c.d.t.SpringBootCurdApplication.logStartupProfileInfo - No active profile set, falling back to default profiles: default
15-03-2022 18:48:00.625 [main] INFO  o.s.b.w.e.tomcat.TomcatWebServer.initialize - Tomcat initialized with port(s): 8080 (http)
15-03-2022 18:48:00.641 [main] INFO  o.a.catalina.core.StandardService.log - Starting service [Tomcat]
15-03-2022 18:48:00.641 [main] INFO  o.a.catalina.core.StandardEngine.log - Starting Servlet engine: [Apache Tomcat/9.0.39]
15-03-2022 18:48:00.844 [main] INFO  o.a.c.c.C.[Tomcat].[localhost].[/].log - Initializing Spring embedded WebApplicationContext
15-03-2022 18:48:00.844 [main] INFO  o.s.b.w.s.c.ServletWebServerApplicationContext.prepareWebApplicationContext - Root WebApplicationContext: initialization completed in 2924 ms
15-03-2022 18:48:01.422 [main] INFO  o.s.s.c.ThreadPoolTaskExecutor.initialize - Initializing ExecutorService 'applicationTaskExecutor'
15-03-2022 18:48:01.828 [main] INFO  o.s.b.w.e.tomcat.TomcatWebServer.start - Tomcat started on port(s): 8080 (http) with context path ''
15-03-2022 18:48:01.844 [main] INFO  c.d.t.SpringBootCurdApplication.logStarted - Started SpringBootCurdApplication in 5.613 seconds (JVM running for 9.056)
15-03-2022 18:48:21.338 [http-nio-8080-exec-2] INFO  o.a.c.c.C.[Tomcat].[localhost].[/].log - Initializing Spring DispatcherServlet 'dispatcherServlet'
15-03-2022 18:48:21.346 [http-nio-8080-exec-2] INFO  o.s.web.servlet.DispatcherServlet.initServletBean - Initializing Servlet 'dispatcherServlet'
15-03-2022 18:48:21.362 [http-nio-8080-exec-2] INFO  o.s.web.servlet.DispatcherServlet.initServletBean - Completed initialization in 16 ms
15-03-2022 18:48:21.414 [http-nio-8080-exec-2] DEBUG c.d.t.s.ProductServicelogBackImpl.getAllProducts - Test debug message
15-03-2022 18:48:24.496 [http-nio-8080-exec-3] DEBUG c.d.t.c.ProductsControllerLogback.testWeb - A DEBUG Message @testWeb
15-03-2022 18:48:24.500 [http-nio-8080-exec-3] INFO  c.d.t.c.ProductsControllerLogback.testWeb - An INFO Message @testWeb
15-03-2022 18:48:24.500 [http-nio-8080-exec-3] WARN  c.d.t.c.ProductsControllerLogback.testWeb - A WARN Message @testWeb
15-03-2022 18:48:24.500 [http-nio-8080-exec-3] ERROR c.d.t.c.ProductsControllerLogback.testWeb - An ERROR Message @testWeb

These are resulting logs of logback form controller and service classes.

Please find the Github repo for Spring-Boot-Logs-Example-App

Leave A Reply