Meet is fate, pass by a praise

Source: https://github.com/yulc-coding/java-note/tree/master/logback

Related articles: Simple use of Spring Boot Log4j2 logs

The function point

  • Generate files by log level

  • Custom generated log files:

    1. Logs that require independent analysis, such as scheduled tasks, are stored in independent files
    2. Generates a separate file for logs of a specified package or class
  • Generate files by date

  • Set the log file size

  • Set the log file expiration time


start

  • Spring Boot uses Logback as the logging framework by default, so there is no need to introduce additional JARS
  • Create a new XML file logback-spring.xml under SRC /main/resources

The basic structure

<configuration> <! -- Define variables to pass${name}Use --> <property name="", value =""></property> <! Log configuration --> <appender></appender> <! Set up specific printouts and reference the appender --> <logger></logger> <! Logger --> <root></root> </configuration>Copy the code
property

Configure custom variables

<! -- Define log file storage address --> <property name="LOG_HOME" value="./logs"/ > <! -- Define log print format --> <property name="LOG_PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%X{user}]-[%X{args}] [%thread] %-5level %logger{50} - %msg%n"/>
Copy the code
appender

Log component, name specifies the appender name, used, and referenced. Class specifies the output method of the appender

  1. Ch. Qos. Logback. Core. ConsoleAppender: printed in the console
<! Console output Settings --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <withJansi>true</withJansi> <! --> <encoder> <! - console color printing - > < pattern > % d {MM - dd yyyy - HH: MM: ss. The SSS} % blue (X {user} [%] - [% X {args}]) %, (thread] [%) % highlight - 5 level (%) %boldMagenta(%logger{50}) - %cyan(%msg%n)</pattern> <charset>utf8</charset> </encoder> </appender>Copy the code
  1. Ch. Qos. Logback. Core. FileAppender: add logging to a file, has been accumulating a file, cause the file is too large, view is not convenient, not recommended

  2. Ch. Qos. Logback. Core. Rolling. RollingFileAppender: scroll records, to log onto a specified file, when accord with a condition, the log records to other documents, such as more than a single file to set the size of the archive logs according to the day

<! -- Set separate log files for scheduled tasks --> <appender name="SCHEDULE-APPENDER" class="ch.qos.logback.core.rolling.RollingFileAppender"> <! -- Name of current log File --> <File>${LOG_HOME}/schedule.log</File>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <! -- Archive log file output file name --> <FileNamePattern>${LOG_HOME}/schedule.%d{yyyy-MM-dd}.%i.log</FileNamePattern> <! MaxHistory </MaxHistory> <! -- the largest size in a single log file -- > < timeBasedFileNamingAndTriggeringPolicy class ="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>5MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> </rollingPolicy> <! Format the log --> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${LOG_PATTERN}</pattern> </encoder> <! -- Prints INFO and above logs --> <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
    </appender>
Copy the code

The preceding information indicates that a new log file is generated every day. If a log file exceeds 5M, a new log file is generated and the log files generated in the last 7 days are reserved

logger

Loggerfactory.getlogger (“schedule”); loggerFactory.getLogger (” Schedule “); Specifies log level additivity: whether content is passed up, if true, otherwise it will also be displayed in the root configuration log

<! The name is the same as the string in the business class getLogger --> < Logger name="schedule" level="INFO" additivity="false">
        <appender-ref ref="SCHEDULE-APPENDER"/> </logger> <! - org. Ylc. Note. Logback. Service package all log under independent printing (can also be assigned to the class) - > < logger name ="org.ylc.note.logback.service" level="INFO" additivity="false">
        <appender-ref ref="SERVICE-APPENDER"/>
    </logger>
Copy the code
root

The root loger, the parent of all Loggers, sets the log component that needs to be printed


Unit testing
@springbooTtest Class LogbackApplicationTests {/** * private Final Logger normalLogger = LoggerFactory.getLogger(LogbackApplicationTests.class); /** * The name of logger must be the same as that of LOGGER in XML. Schedule */ Private Final Logger scheduleLogger = LoggerFactory.getLogger("schedule"); @Autowired private MyService myService; /** * normal log Test */ @test voidnormalLogTest() {
        normalLogger.info("this is a info log with out args");
        normalLogger.error("this is a error log with out args"); } /** * log Test with parameters */ @test voidargsLogTest() {
        MDC.put("user".Fish Fairy);
        MDC.put("args"."Parameters");
        normalLogger.info("this is a info log with args");
        normalLogger.error("this is a error log with args"); } /** * Test for independent logs * 1, specify log name * 2, specify package or class */ @test voidindependentLogTest() {// Specify the name schedulelogger.info ("this is a schedule info log");
        scheduleLogger.error("this is a schedule error log"); // Specify the package or class myservice.mylog (); }}Copy the code

Please focus on