SpringBoot configuration logback

The logging configuration of a project is a common case. The previous contact and use are Spring combined with XML, introduce a few dependencies, and then write logback. XML configuration file, so what can be done in SpringBoot?

I. Configuration description

In the resource directory, create a new log file: logback-spring.xml. The content is as follows

<?xml version="1.0" encoding="UTF-8"? >
<configuration>
    <! - % m output information, % p log level, % t thread name, date of % d, % c's full name, % I index [increasing from 0],,, -- -- >
    <! An appender is a child of a configuration node and is the component responsible for writing logs. -->
    <! -- ConsoleAppender: Output logs to the console -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d [%t] %-5level %logger{36}.%M\(%file:%line\) - %msg%n</pattern>
            <! -- Console use UTF-8, not GBK, otherwise Chinese garbled -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <appender name="errorAlarm" class="com.git.hui.story.common.alarm.ServiceAlarm">
        <! -- If you only want Error logs, then you need to filter them, default is info, ThresholdFilter-->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>ERROR</level>
        </filter>
    </appender>

    <! -- RollingFileAppender: Scroll a file, log to a specified file first, and log to another file when a condition is met -->
    <! * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    <! -- 2. If the date has not changed, but the current log file size exceeds 1KB, split and rename the current log -->
    <appender name="story" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <! -- If you only want Error logs, then you need to filter them, default is info, ThresholdFilter-->
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
        <File>logs/story.log</File>
        <! -- rollingPolicy: Determines the behavior of a RollingFileAppender when scrolling occurs, involving file movement and renaming. -->
        <! -- TimeBasedRollingPolicy: The most commonly used rollingpolicy. It sets the rollingpolicy according to the time, and is responsible for both the rolling and the starting of the rolling -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <! -- The name of the active file is changed every once in a while, based on the value of fileNamePattern -->
            <! 2018-06-23.0.log -->
            <fileNamePattern>logs/arch/story.%d.%i.log</fileNamePattern>
            <! -- Each log file generated, the log file is saved for 3 days -->
            <maxHistory>3</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <! -- maxFileSize: This is the size of the active file, default is 10MB, test can be changed to 1KB to see the effect -->
                <maxFileSize>10MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <encoder>
            <! -- pattern node, which sets the log input format -->
            <pattern>
                %d %p (%file:%line\)- %m%n
            </pattern>
            <! -- Log encoding: set character set here -->
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <! -- Specify the logging level of a package in a project when logged operations are performed -->
    <! -- FATAL > ERROR > WARN > INFO > DEBUG > TRACE -->
    <! -- apptivity =false =false -->
    <logger name="com.git.hui" level="DEBUG" additivity="false">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="story"/>
        <appender-ref ref="errorAlarm"/>
    </logger>

    <logger name="com.github.hui" level="DEBUG" additivity="false">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="story"/>
        <appender-ref ref="errorAlarm"/>
    </logger>

    <! -- Console output log level -->
    <root level="INFO">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>
Copy the code

Above is a basic log output configuration, with a few additional notes:

  • Whether the configuration file name is different
  • inappenderLog levels are filtered in labels
  • aloggerThere are more than one under the labelappender-ref
  • Custom appender implementation classes

II. The extension

1. Configure the file name

The configuration file name defaults to logback-spring.xml. What if I want to change it to mylog.xml?

Modify parameter specifications in the application.yml configuration file

logging:
  config: classpath:mylog.xml
Copy the code

2. The logger

The logger label can be attached with multiple

appenders, which means that the matched logs will be printed. For example, an error log will be printed in the console and in the log file. If the error log is generated, ServiceAlarm will be triggered

The problem is that we might want to have different internal log level controls. For example, the console can output debug logs, but the log file only outputs info logs. This would require adding the Filter attribute in the appender tag

<appender name="errorLog" class="ch.qos.logback.core.rolling.RollingFileAppender"> <! -- ThresholdFilter--> <filter class= info --> <filter class= info --> <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
        <level>WARN</level>
    </filter>
</appender>
Copy the code

3. Customize the appender implementation class

In the preceding configuration file, a custom AlarmService is used to realize custom alarm when error logs are received. The simple implementation is as follows

/** * alarm * Created by@author yihui in 16:43 18/6/23.
 */
public class ServiceAlarm extends AppenderBase<ILoggingEvent> {
    private static final long INTERVAL = 10 * 1000 * 60;
    private long lastAlarmTime = 0;

    @Override
    protected void append(ILoggingEvent iLoggingEvent) {
        if(canAlarm()) { doAlarm(iLoggingEvent.getFormattedMessage()); }}private boolean canAlarm(a) {
        long now = System.currentTimeMillis();
        if (now - lastAlarmTime >= INTERVAL) {
            lastAlarmTime = now;
            return true;
        } else {
            return false; }}private void doAlarm(String content) {
        try {
            EmailWrapper.sendMail("Abnormal alarm"."[email protected]", content);
        } catch(Exception e) { e.printStackTrace(); }}}Copy the code

4. Other

For details on the parameters in the Logback configuration file, see the blog post:

  • Logback concise user manual

III. The other

1. A gray Blog: https://liuyueyi.github.io/hexblog.

A gray personal blog, record all study and work in the blog, welcome everyone to visit

2. Statement

The letter is not as good as the book, has been on the content, purely a statement, due to the limited personal ability, there are inevitably omissions and mistakes, such as found bugs or better suggestions, welcome criticism and correction, not grudging gratitude

  • Micro-blog address: small gray Blog
  • QQ: A gray /3302797840

3. Scan for attention