Introduction of Logback

Logback is another logging framework after Log4j. Logback is a logging framework provided by SpringBoot. Logback distinguishes different log levels with strict log levels (other log levels are inherited from the previous log level, for example: Log4j2, log4j both inherit higher levels of logging), logback is divided into three modules, logback-core, logback-classic, logback-access.

  • Logback-core: Logback-core is the core module of logback, which is the basis of logback-classic and logback-access.
  • Logback-classic: The SLF4J API is implemented and used with SLF4J to easily switch to other logging frameworks.
  • Logback-access: Integrates with Servlet containers (such as Tomcat and Jetty) and provides an HTTP access logging interface.

Springboot integration logback

As mentioned earlier, since SpringBoot itself is integrated with LogBack, the integration of Logback requires only springBoot’s own dependencies.

Pom depends on

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>
Copy the code

Configuration of the application.properties file

logging.config=classpath:logback-spring.xml
Copy the code

Logback-spring. XML file configuration

<?xml version="1.0" encoding="UTF-8"? >
<configuration scan="true" scanPeriod="60 seconds">
    <property name="LOG_HOME" value="./WebAppLogs/logs"/>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <! Format output: %d indicates the date, %thread indicates the thread name, %-5level indicates the level of 5 characters from the left. % MSG indicates the log message, %n indicates the newline character.
            <pattern>[%d{HH:mm:ss:SSS}] - [%t] [%p] - %logger{36} - %m%n</pattern>
        </encoder>
    </appender>

    <! -- Trace log -->
    <appender name="RollingFileTrace" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <file>${LOG_HOME}/trace.log</file>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <! -- Only trace logs are accepted. Because logBack has strict log classification, only trace logs of this type are accepted -->
            <level>TRACE</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/trace_%d{yyyy-MM-dd-HH}-%i.log.zip</fileNamePattern>
            <! -- Single file size -->
            <maxFileSize>10 MB</maxFileSize>
            <! FileNamePattern = yyyY-MM-DD-HH; fileNamePattern = YYYY-MM-DD-HH;
            <maxHistory>168</maxHistory>
            <! -- Total file log -->
            <totalSizeCap>10GB</totalSizeCap>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <! Format output: %d indicates the date, %thread indicates the thread name, %-5level indicates the level of 5 characters from the left. % MSG indicates the log message, %n indicates the newline character.
            <pattern>[%d{HH:mm:ss:SSS}] - [%t] [%p] - %logger{36} - %m%n</pattern>
            <! Set log encoding to UTF-8 -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <! -- Debug log -->
    <appender name="RollingFileDebug" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <file>${LOG_HOME}/debug.log</file>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>DEBUG</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/debug_%d{yyyy-MM-dd-HH}-%i.log.zip</fileNamePattern>
            <! -- Single file size -->
            <maxFileSize>10 MB</maxFileSize>
            <! FileNamePattern = yyyY-MM-DD-HH; fileNamePattern = YYYY-MM-DD-HH;
            <maxHistory>168</maxHistory>
            <! -- Total file log -->
            <totalSizeCap>10GB</totalSizeCap>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <! Format output: %d indicates the date, %thread indicates the thread name, %-5level indicates the level of 5 characters from the left. % MSG indicates the log message, %n indicates the newline character.
            <pattern>[%d{HH:mm:ss:SSS}] - [%t] [%p] - %logger{36} - %m%n</pattern>
            <! Set log encoding to UTF-8 -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <! -- info log -->
    <appender name="RollingFileInfo" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <file>${LOG_HOME}/info.log</file>
            <! -- As long as the info log configuration -->
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/info_%d{yyyy-MM-dd-HH}-%i.log.zip</fileNamePattern>
            <! -- Single file size -->
            <maxFileSize>10 MB</maxFileSize>
            <! FileNamePattern = yyyY-MM-DD-HH; fileNamePattern = YYYY-MM-DD-HH;
            <maxHistory>168</maxHistory>
            <! -- Total file log -->
            <totalSizeCap>10GB</totalSizeCap>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <! Format output: %d indicates the date, %thread indicates the thread name, %-5level indicates the level of 5 characters from the left. % MSG indicates the log message, %n indicates the newline character.
            <pattern>[%d{HH:mm:ss:SSS}] - [%t] [%p] - %logger{36} - %m%n</pattern>
            <! Set log encoding to UTF-8 -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <! -- WARN logs -->
    <appender name="RollingFileWarn" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <file>${LOG_HOME}/warn.log</file>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>WARN</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/warn_%d{yyyy-MM-dd-HH}-%i.log.zip</fileNamePattern>
            <! -- Single file size -->
            <maxFileSize>10 MB</maxFileSize>
            <! FileNamePattern = yyyY-MM-DD-HH; fileNamePattern = YYYY-MM-DD-HH;
            <maxHistory>168</maxHistory>
            <! -- Total file log -->
            <totalSizeCap>10GB</totalSizeCap>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <! Format output: %d indicates the date, %thread indicates the thread name, %-5level indicates the level of 5 characters from the left. % MSG indicates the log message, %n indicates the newline character.
            <pattern>[%d{HH:mm:ss:SSS}] - [%t] [%p] - %logger{36} - %m%n</pattern>
            <! Set log encoding to UTF-8 -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <! -- error log -->
    <appender name="RollingFileError" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <file>${LOG_HOME}/error.log</file>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/error_%d{yyyy-MM-dd-HH}-%i.log.zip</fileNamePattern>
            <! -- Single file size -->
            <maxFileSize>10 MB</maxFileSize>
            <! FileNamePattern = yyyY-MM-DD-HH; fileNamePattern = YYYY-MM-DD-HH;
            <maxHistory>168</maxHistory>
            <! -- Total file log -->
            <totalSizeCap>10GB</totalSizeCap>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <! Format output: %d indicates the date, %thread indicates the thread name, %-5level indicates the level of 5 characters from the left. % MSG indicates the log message, %n indicates the newline character.
            <pattern>[%d{HH:mm:ss:SSS}] - [%t] [%p] - %logger{36} - %m%n</pattern>
            <! Set log encoding to UTF-8 -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <! -- App Log -->
    <appender name="RollingFileApp" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <file>${LOG_HOME}/app.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/app_%d{yyyy-MM-dd-HH}-%i.log.zip</fileNamePattern>
            <! -- Single file size -->
            <maxFileSize>10 MB</maxFileSize>
            <! FileNamePattern = yyyY-MM-DD-HH; fileNamePattern = YYYY-MM-DD-HH;
            <maxHistory>168</maxHistory>
            <! -- Total file log -->
            <totalSizeCap>10GB</totalSizeCap>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <! Format output: %d indicates the date, %thread indicates the thread name, %-5level indicates the level of 5 characters from the left. % MSG indicates the log message, %n indicates the newline character.
            <pattern>[%d{HH:mm:ss:SSS}] - [%t] [%p] - %logger{36} - %m%n</pattern>
            <! Set log encoding to UTF-8 -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <logger name="org.springframework" level="info"/>
    <! -- Use log inheritance addtivity="false" -->
    <logger name="com.javanorth" level="all" addtivity="true"/>

    <root level="info">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="RollingFileTrace"/>
        <appender-ref ref="RollingFileDebug"/>
        <appender-ref ref="RollingFileInfo"/>
        <appender-ref ref="RollingFileWarn"/>
        <appender-ref ref="RollingFileError"/>
        <appender-ref ref="RollingFileApp"/>
    </root>
</configuration>
Copy the code

Configuration to write all logs to a log file

<?xml version="1.0" encoding="UTF-8"? >
<configuration scan="true" scanPeriod="60 seconds">
    <property name="LOG_HOME" value="./WebAppLogs/logs"/>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <! Format output: %d indicates the date, %thread indicates the thread name, %-5level indicates the level of 5 characters from the left. % MSG indicates the log message, %n indicates the newline character.
            <pattern>[%d{HH:mm:ss:SSS}] - [%t] [%p] - %logger{36} - %m%n</pattern>
        </encoder>
    </appender>

    <! -- App Log -->
    <appender name="RollingFileApp" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <append>true</append>
        <file>${LOG_HOME}/app.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/app_%d{yyyy-MM-dd-HH}-%i.log.zip</fileNamePattern>
            <! -- Single file size -->
            <maxFileSize>10 MB</maxFileSize>
            <! FileNamePattern = yyyY-MM-DD-HH; fileNamePattern = YYYY-MM-DD-HH;
            <maxHistory>168</maxHistory>
            <! -- Total file log -->
            <totalSizeCap>10GB</totalSizeCap>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <! -- Formatted output: %d for date, %t for thread name, % MSG for log message, %n for newline -->
            <pattern>[%d{HH:mm:ss:SSS}] - [%t] [%p] - %logger{36} - %m%n</pattern>
            <! Set log encoding to UTF-8 -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <logger name="org.springframework" level="info"/>
    <! -- Use log inheritance addtivity="false" -->
    <logger name="com.javanorth" level="all" addtivity="true"/>

    <root level="info">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="RollingFileApp"/>
    </root>
</configuration>
Copy the code

Logback logging is implemented through SLF4J

public class LogUtil {

    /** * Debug level log output *@paramClazz class *@paramMSG log *@paramParams Other parameters */
    public static void debug(Class clazz, String msg, Object... params) {
        Logger logger = LoggerFactory.getLogger(clazz.getName());
        logger.debug(msg, params);
    }

    /** * Trace log output *@paramClazz class *@paramMSG log *@paramParams Other parameters */
    public static void trace(Class clazz, String msg, Object... params) {
        Logger logger = LoggerFactory.getLogger(clazz.getName());
        logger.trace(msg, params);
    }

    /** * info level log output *@paramClazz class *@paramMSG log *@paramParams Other parameters */
    public static void info(Class clazz, String msg, Object... params) {
        Logger logger = LoggerFactory.getLogger(clazz.getName());
        logger.info(msg, params);
    }

    /** * WARN logs are generated *@paramClazz class *@paramMSG log *@paramParams Other parameters */
    public static void warn(Class clazz, String msg, Object... params) {
        Logger logger = LoggerFactory.getLogger(clazz);
        logger.warn(msg, params);
    }

    /** * Error level log output *@paramClazz class *@paramMSG log *@paramParams Other parameters */
    public static void error(Class clazz, String msg, Object... params) { Logger logger = LoggerFactory.getLogger(clazz); logger.error(msg, params); }}Copy the code

Slf4j implementation

void contextLoads(a) {
    LogUtil.info(this.getClass(), "this is info log");
}
Copy the code

Log output

conclusion

In general, logback is somewhat worse than log4j2 in terms of performance, as we’ve analyzed in previous articles, but logback is still popular with many people. Personally, logback configuration is simpler than log4j2 and logback logging is simpler. And the log inheritance requirements are very strict, which to a certain extent to facilitate problem finding and reduce unnecessary log.

Refer to the article

  • [1]. The use of logback and logback. XML, rounding. www.cnblogs.com/warking/p/5… .
  • [2]. Logback website. Logback. Qos. Ch/documentati… .