Spring Boot Integrates slf4j and logback

The difference between slf4j and logback.

  1. Slf4j (Simple Logging Facade for Java) is a log facade of Java that implements some common apis for the logging framework.
  2. Logback is the specific logging framework. It has the same author as log4j, the new logging framework developed to address the problems of log4j.
  3. Slf4j and logback can simply be thought like the relationship between JDBC and the JDBC’s jar package for specific database.
  4. Slf4j is recommended instead of directly using logback.
  5. slf4j code example:
    log.info("Begin Start {}...{}", str1, str2);
  6. logback code example:
    log.info("Begin Start " + str1 +"..." + str2);
  7. As example above, sl4j is better than logback in both writing and performance.

Spring Boot Integration Log

  1. POM.xml
  2. logback-spring.xml
    <?xml version="1.0" encoding="UTF-8"?> 
     <!--Define log file store path. Do not use the relative path --> 
     <property name="LOG_HOME" value="/tmp/log" /> 
     <!-- Log output in console configuration --> 
     <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> 
           <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> 
               <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{30} - %msg%n</pattern> 
     <!-- Log data in file configuration. Generate log files per day --> 
     <appender name="FILE" 
            <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> 
               <!-- Log files remain 30 days maximam --> 
            <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> 
                <!--Log format :%d : day, %thread : log thread name, %-5level:Log level info shows only five character widths from the left, %msg:log message, %n: newline --> 
                <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{30} - %msg%n</pattern> 
            <!--The maximum size of log files is 10MB --> 
            <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> 
     <!-- Log output level. Defines the root logger, specify the appender defined by appender-ref --> 
     <root level="INFO"> 
         <appender-ref ref="STDOUT" /> 
         <appender-ref ref="FILE" /> 
     <!-- Defines the detailed path of each package, inheriting the value of the root package --> 
     <logger name="com.dev2qa.spring.log" level="INFO" /> 
     <logger name="com.dev2qa.spring" level="TRACE" /> 
     <!-- This value is specified by spring.profiles.active=dev of application.properties --> 
     <springProfile name="dev"> 
          <!--Define log file save path. Do not use relative path in logback configuration --> 
          <property name="LOG_HOME" value="/tmp/log" /> 
          <logger name="org.springboot.sample" level="ERROR" /> 
     <springProfile name="pro"> 
          <!--Define log file save path. Do not use relative path in logback configuration --> 
          <property name="LOG_HOME" value="/home" /> 
          <logger name="org.springboot.sample2" level="INFO" /> 

    Appender name=”STDOUT”: Log to the console.

    Appender name=”FILE” : The log data is printed to FILE on a daily basis, with MaxHistory days retained, and MaxFileSize per FILE.

    Encoder: defines the output format.
    %d{HH:mm:ss.SSS} – log output time.
    %thread – the name of the process that exports the logs, which is useful in Web applications and asynchronous task processing.
    %-5level – log level, left aligned with 5 characters.
    %logger{36} — the name of the log exporter.
    %msg – log message.
    %n – new line charactor of the running platform.

    <springProfile name=”dev”> :Define the value of profile. The content defined here only works when particular profile is defined in application.properties such as spring.profiles.active=dev.

  3. application.properties
    # This key's value decide which logback configuration will be used.
    # Because the value is dev then the content under 
    # <springProfile name="dev"> in logback-spring.xml will take effect.
  4. Sample Code.
    import org.springframework.boot.SpringApplication;  
    import org.springframework.boot.autoconfigure.SpringBootApplication; 
    import org.slf4j.Logger;  
    import org.slf4j.LoggerFactory;   
    public class LogApplication { 
        // Get logger object use LoggerFactory. 
        private static final Logger log = LoggerFactory.getLogger(LogApplication.class);  
        public static void main(String[] args) {  
            String str1 = "string1";  
            String str2 = "string2";  
            log.info("Begin Start {}...{}", str1, str2);  
            SpringApplication.run(LogApplication.class, args);  
            log.info("Stop ...");  
  5. Startup service.
    Spring boot can also start the specified profile use command line:
    java -jar log.jar --spring.profiles.active=dev
    If you do not specify an active value in boot command, use the value in application.properties.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.