x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Spring Boot Logging with Logback SLF4J

    Spring Boot uses SLF4J as logging API & Logback as default logging provider but also supports configuration for Log4j2 and Java Util logging frameworks. This Spring Boot logging example shows how to configure log levels in a Spring Boot application.

    Step 1) Create application.properties file (under src/main/resources ) to set logging level. Note that root level logging level is the default logging level.

    logging.level.root=INFO
    logging.level.com.example.demo=INFO
    logging.level.org.springframework.web=INFO        

    Maven Build












    Step 2) Create SpringBootLoggingExample class

    We will use SLF4J logging API to log the messages, so that we can switch to any logging framework like logback or log4j2 without any code changes. When run, SpringBootLoggingExample class will print logs with the level set in application.properties file.

    package com.example.demo;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class SpringBootLoggingExample {
    	
        private static Logger logger = LoggerFactory.getLogger(SpringBootLoggingExample.class);
    
        public static void main(String[] args) {
            SpringApplication.run(SpringBootLoggingExample.class, args);
            logger.trace("Spring Boot app started");
            logger.warn("Spring Boot app started");
            logger.info("Spring Boot Logging Example");
            logger.debug("Spring Boot app starting");    }
    }        

    Step 3) Running SpringBootLoggingExample

    To Run this Spring Boot application from command prompt, use following command → java -jar demo-0.0.1-SNAPSHOT.jar

    Output :

    2021-02-02 13:23:02.317  INFO 9304 --- [main] c.example.demo.SpringBootLoggingExample  : Started SpringBootLoggingExample in 1.601 seconds (JVM running for 2.34)
    2021-02-02 13:23:02.320  WARN 9304 --- [main] c.example.demo.SpringBootLoggingExample  : Spring Boot app started
    2021-02-02 13:23:02.321  INFO 9304 --- [main] c.example.demo.SpringBootLoggingExample  : Spring Boot Logging Example
    

    Step 4) Change logging level in application.properties to DEBUG and rerun the application.

    You can play with the root level logging as per your logging requirements. Try to change it to ERROR, WARN, INFO, DEBUG and see the output.

    logging.level.root=INFO
    logging.level.com.example.demo=DEBUG
    logging.level.org.springframework.web=INFO

    Output :

    2021-02-02 13:24:57.373  INFO 16084 --- [main] c.example.demo.SpringBootLoggingExample  : No active profile set, falling back to default profiles: default
    2021-02-02 13:24:58.248  INFO 16084 --- [main] c.example.demo.SpringBootLoggingExample  : Started SpringBootLoggingExample in 1.421 seconds (JVM running for 2.121)
    2021-02-02 13:24:58.253  WARN 16084 --- [main] c.example.demo.SpringBootLoggingExample  : Spring Boot app started
    2021-02-02 13:24:58.254  INFO 16084 --- [main] c.example.demo.SpringBootLoggingExample  : Spring Boot Logging Example
    2021-02-02 13:24:58.255 DEBUG 16084 --- [main] c.example.demo.SpringBootLoggingExample  : Spring Boot app starting 

    Step 5) In case you want to write the logs to a file, then you need to change application.properties as shown below

    logging.level.root=INFO
    logging.level.com.example.demo=INFO
    logging.level.org.springframework.web=INFO        
    logging.file=application.log
    logging.path=/tmp/log        

    Using logback-spring.xml to configure logging

    You can use application.properties for basic configuration, but if you want advanced logging configuration, then you need to create a logback-spring.xml file. Using xml file you can specify whether you want to log to console or a file by providing the appropriate appender. You can also specify the log pattern using pattern and can set the log level.
    Create logback-spring.xml file (under src/main/resources) to set advanced logging configuration for production enviornment.

    To know details of log patterns you can visit this page Logback layouts
    <?xml version="1.0" encoding="UTF-8"?>
    <configuration>
    
        <property name="HOME_LOG" value="logs/app.log"/>
    
        <appender name="FILE-ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
            <file>${HOME_LOG}</file>
    
            <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
                <fileNamePattern>logs/archived/app.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
                <maxFileSize>10MB</maxFileSize>
                <totalSizeCap>10GB</totalSizeCap>
                <maxHistory>30</maxHistory>
            </rollingPolicy>
    
            <encoder>
                <pattern>%d [%thread] %-5level %logger{36} - %msg%n</pattern>
            </encoder>
        </appender>
    
        <logger name="com.example.demo" level="debug" additivity="false">
            <appender-ref ref="FILE-ROLLING"/>
        </logger>
    
        <root level="error">
            <appender-ref ref="FILE-ROLLING"/>
        </root>
    
    </configuration>        

    Log file Output (see app.log unders logs directory):

    2019-10-27 16:23:41,954 [main] INFO  c.e.demo.SpringBootLogbackExample - Starting SpringBootLogbackExample on ssss-PC with PID 5580 (C:\Dev\eclipse\workspace\SpringBoot\target\classes started by sss in C:\Dev\eclipse\workspace\SpringBoot)
    2019-10-27 16:23:41,956 [main] INFO  c.e.demo.SpringBootLogbackExample - No active profile set, falling back to default profiles: default
    2019-10-27 16:23:43,597 [main] INFO  o.s.b.w.e.tomcat.TomcatWebServer - Tomcat initialized with port(s): 8080 (http)
    2019-10-27 16:23:43,622 [main] INFO  o.a.coyote.http11.Http11NioProtocol - Initializing ProtocolHandler ["http-nio-8080"]
    2019-10-27 16:23:43,640 [main] INFO  o.a.catalina.core.StandardService - Starting service [Tomcat]
    2019-10-27 16:23:43,640 [main] INFO  o.a.catalina.core.StandardEngine - Starting Servlet engine: [Apache Tomcat/9.0.21]
    2019-10-27 16:23:43,783 [main] INFO  o.a.c.c.C.[Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
    2019-10-27 16:23:43,784 [main] INFO  o.s.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 1759 ms
    2019-10-27 16:23:44,107 [main] INFO  o.s.s.c.ThreadPoolTaskExecutor - Initializing ExecutorService 'applicationTaskExecutor'
    2019-10-27 16:23:44,359 [main] INFO  o.a.coyote.http11.Http11NioProtocol - Starting ProtocolHandler ["http-nio-8080"]
    2019-10-27 16:23:44,392 [main] INFO  o.s.b.w.e.tomcat.TomcatWebServer - Tomcat started on port(s): 8080 (http) with context path ''
    2019-10-27 16:23:44,396 [main] INFO  c.e.demo.SpringBootLogbackExample - Started SpringBootLogbackExample in 3.22 seconds (JVM running for 3.707)
             

    Using another logging provider

    Bu default, Spring Boot uses Logback as logging provider. You can also use another logging provider like Log4J2 or Java Util Logging. To use another logging provider, you first need to exclude spring-boot-starter-logger maven dependency which is provided as default by Spring Boot framework. After that you need to add the requied dependency like spring-boot-starter-log4j2. Since we use SLF4J as logging API, it will automatically pick up Log4J2 as logging provider as shown in below code.

    private static Logger logger = LoggerFactory.getLogger(SpringBootLoggingExample.class);
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>		
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>		


    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *











    Share This