SpringBoot Logging using Logback

By default, Spring Boot uses Logback for the logging, and the loggers are pre-configured to use console output with optional file output.

Logback will provide below logging levels which has been defined in below order.

  1. TRACE
  2. DEBUG
  3. INFO
  4. WARN
  5. ERROR
  6. OFF
  1. 1. When we set the log level to INFO (default), it logs the INFO, WARN, and ERROR log events.
  2. 2. When we set the log level to DEBUG, it logs the DEBUG, INFO, WARN, and ERROR log events.
  3. 3. When we set the log level to ERROR, it logs only the ERROR log events.

Log Example

                    @RestController
                    public class CustomerController {
                        private static final Logger logger = LoggerFactory.getLogger(CustomerController.class);

                        @GetMapping("/")
                        public String printMessage() {
                            logger.debug("Debug level - Hello Logback");
                            logger.info("Info level - Hello Logback");
                            logger.error("Error level - Hello Logback");
                            return "Hello Logback";
                        }
                    }
                  

Log Variable

We can use {} to log the variables in spring boot application.


                    @RestController
                    public class CustomerController {
                        private static final Logger logger = LoggerFactory.getLogger(CustomerController.class);

                        @GetMapping("/getMessage/{message}")
                        public String printMessage(@PathVariable String message) {
                            logger.debug("Debug level - Hello Logback {}", name);
                            logger.info("Info level - Hello Logback {}", name);
                            logger.error("Error level - Hello Logback {}", name);
                            return "Hello Logback" +message;
                        }
                    }
                  

Log to File

By default, SpringBoot does not write logs to files, in case if we want to write to logs to files then we need to provide logging.file.name or logging.file.path property in the application.properties or application.yml.


                    logging.file.name=logs/app.log
                  

File Rotation

For Logback, we can configure the file rotation directly in the application.properties or application.yml. The configuration file below will rotate or roll based on file size and date time.


                    
                  logging.file.name=logs/app.log

                  #The filename pattern used to create log archives.
                  logging.logback.rollingpolicy.file-name-pattern=logs/%d{yyyy-MM, aux}/app.%d{yyyy-MM-dd}.%i.log

                  #The maximum size of log file before it is archived.
                  logging.logback.rollingpolicy.max-file-size=100MB

                  #The maximum amount of size log archives can take before being deleted.
                  logging.logback.rollingpolicy.total-size-cap=10GB

                  #The maximum number of archive log files to keep (defaults to 7).
                  logging.logback.rollingpolicy.max-history=10

                  

Native logback.xml

SpringBoot supports the native configuration file, we need to prepare and put the logback.xml in the resources folder, and Spring Boot will auto-detect it.


                    <?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/%d{yyyy-MM, aux}/app.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
                                <!-- each archived file, size max 10MB -->
                                <maxFileSize>10MB</maxFileSize>
                                <!-- total size of all archive files, if total size > 20GB, it will delete old archived file -->
                                <totalSizeCap>20GB</totalSizeCap>
                                <!-- 60 days to keep -->
                                <maxHistory>60</maxHistory>
                            </rollingPolicy>

                            <encoder>
                                <pattern>%d %p %c{1.} [%t] %m%n</pattern>
                            </encoder>
                        </appender>

                        <logger name="com.mkyong" level="debug" additivity="false">
                            <appender-ref ref="FILE-ROLLING"/>
                        </logger>

                        <root level="error">
                            <appender-ref ref="FILE-ROLLING"/>
                        </root>

                    </configuration>

                  

logback-spring.xml

Spring Boot Logbak extensions, use the logback-spring.xml configuration file. Create logback-spring.xml and put it under the resources folder to enable the profile level logging
Below is a Spring Boot profile-specific logging example:

  1. 1. If no active profile (default), or active profiles are dev, staging, or test, logs to the console.
  2. 2. If the profile is production, logs to rolling files.


                    <?xml version="1.0" encoding="UTF-8"?>
                    <configuration>
                        <include resource="org/springframework/boot/logging/logback/defaults.xml" />
                        
                        <springProfile name="default | dev | staging | test">
                            <include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
                            <root level="INFO">
                                <appender-ref ref="CONSOLE"/>
                            </root>
                        </springProfile>

                        <springProfile name="production">
                            <appender name="FILE-ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
                                <file>/Users/mkyong/logs/prod.log</file>

                                <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
                                    <fileNamePattern>/Users/mkyong/logs/%d{yyyy-MM, aux}/prod.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
                                    <!-- each archived file, size max 10MB -->
                                    <maxFileSize>10MB</maxFileSize>
                                    <!-- total size of all archive files, if total size > 20GB, it will delete old archived file -->
                                    <totalSizeCap>20GB</totalSizeCap>
                                    <!-- 60 days to keep -->
                                    <maxHistory>60</maxHistory>
                                </rollingPolicy>

                                <encoder>
                                    <pattern>%d %p %c [%t] %m%n</pattern>
                                </encoder>
                            </appender>

                            <logger name="org.springframework.web" level="DEBUG"/>
                            <logger name="com.mkyong" level="DEBUG"/>
                            <root level="ERROR">
                                <appender-ref ref="FILE-ROLLING"/>
                            </root>
                        </springProfile>

                    </configuration>
                  

The order of application.properties, logback.xml, and logback-spring.xml?

In Spring Boot, we can use different configuration files, such as application.properties, logback.xml, and logback-spring.xml. Spring Boot defined the order like this:

  1. 1. logback-spring.xml has the highest priority; it supports Spring Profiles.
  2. 2. If the logback-spring.xml is absent, Spring Boot looks for logback.xml, the standard configuration file Logback uses.
  3. 3. Both application.properties and application.yml are used for general Spring Boot configuration. If logback-spring.xml or logback.xml are present, they take precedence, and the settings in application.properties or application.yml supplement or override certain logging configurations (like log levels).

SpringBoot Logback supports

  1. Use logback-spring.xml to support Spring Profiles or the profile-specific logging features.
  2. Use logback.xml if there is no need to use the Spring profile.
  3. Use application.properties for a simple console or file logging.