当前位置:网站首页>Logback log framework

Logback log framework

2022-06-11 00:55:00 Mr_ Jin.

advantage :

It is faster than all existing logging systems , And it takes up less space , It also provides unique and useful features that are not available in other logging systems .

logback To configure

Used in projects logback when , It will default to the project classpath Path down press In order to find be known as logback-test.xml、logback.groovy、logback.xml Configuration file for , If none of the above documents is found , Then use the default configuration ( The default log output level is debug).

configuration


<configuration> yes logback Root node of profile , Yes scan、sacnPeriod、debug、packagingData Equal attribute .

· debug: When this property is set to true when , Will print out logback Internal log information , Real-time view logback Running state . The default value is false.( by true Time and above MyApp1 Of main The two lines of code added to the method have the same effect )
· scan: When this property is set to true when , If the configuration file changes , Will be reloaded , The default value is true.
· scanPeriod: Set the scan profile interval , The default unit is milliseconds . When scan by true when , This property takes effect . The default time interval is 1 minute .
 

An example configuration is as follows :

<configuration scan="true" scanPeriod="60 seconds" debug="false" packagingData="false">
  ...
</configuration>

 

Here are some common Appender

  • ConsoleAppender

ConsoleAppender, seeing the name of a thing one thinks of its function , Output... On the console . Example :

<configuration>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- encoders are assigned the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
    <encoder>
      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern>
    </encoder>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>
  • FileAppender
    FileAppender, One OutputStreamAppender Subclasses of , The function is to output the log to a file . The target file can specify , If the file already exists , It will be appended or truncated according to the value of the attached attribute . Example :
<configuration>

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>testFile.log</file>
    <append>true</append>
    <!-- set immediateFlush to false for much higher logging throughput -->
    <immediateFlush>true</immediateFlush>
    <!-- encoders are assigned the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
    <encoder>
      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
    </encoder>
  </appender>
        
  <root level="DEBUG">
    <appender-ref ref="FILE" />
  </root>
</configuration>

 Uniquely named files (by timestamp)
In the application development phase or short-term application ( For example, batch applications ) period , You want to create a new log file when each new application starts . This is easy to do with the help of elements . Example :

<configuration>

  <!-- Insert the current time formatted as "yyyyMMdd'T'HHmmss" under
       the key "bySecond" into the logger context. This value will be
       available to all subsequent configuration elements. -->
  <timestamp key="bySecond" datePattern="yyyyMMdd'T'HHmmss"/>

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <!-- use the previously created timestamp to create a uniquely
         named log file -->
    <file>log-${bySecond}.txt</file>
    <encoder>
      <pattern>%logger{35} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="FILE" />
  </root>
</configuration>

 

· RollingFileAppender
RollingFileAppender take FileAppender To expand the function of , The function of cutting log file is provided . for example ,RollingFileAppender You can log to a file named log.txt The file of , Once certain conditions are met , Change its log destination to another file .
When use ,RollingFileAppender Must have both RollingPolicy and TriggeringPolicy Set up . however , If it's RollingPolicy It also realizes TriggeringPolicy Interface , Then you only need to explicitly specify the former .

· TimeBasedRollingPolicy
The time base rolling strategy is probably the most popular rolling strategy . It defines a time-based rolling strategy , For example, daily or monthly . The rolling strategy of time bears the responsibility of turnover , At the same time, it also undertakes the triggered rolling .TimeBasedTriggeringPolicy Realized RollingPolicy and TriggeringPolicy Interface .
 

<configuration>
  <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>logFile.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
      <!-- daily rollover -->
      <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>

      <!-- keep 30 days' worth of history capped at 3GB total size -->
      <maxHistory>30</maxHistory>
      <totalSizeCap>3GB</totalSizeCap>

    </rollingPolicy>

    <encoder>
      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
    </encoder>
  </appender> 

  <root level="DEBUG">
    <appender-ref ref="FILE" />
  </root>
</configuration>
  • SizeAndTimeBasedRollingPolicy
    Sometimes you may want to archive files by date , But at the same time, limit the size of each log file , You can use it SizeAndTimeBasedRollingPolicy Achieve a goal .
  • <configuration>
      <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>mylog.txt</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
          <!-- rollover daily -->
          <fileNamePattern>mylog-%d{yyyy-MM-dd}.%i.txt</fileNamePattern>
           <!-- each file should be at most 100MB, keep 60 days worth of history, but at most 20GB -->
           <maxFileSize>100MB</maxFileSize>    
           <maxHistory>60</maxHistory>
           <totalSizeCap>20GB</totalSizeCap>
        </rollingPolicy>
        <encoder>
          <pattern>%msg%n</pattern>
        </encoder>
      </appender>
    
    
      <root level="DEBUG">
        <appender-ref ref="ROLLING" />
      </root>
    
    </configuration>
    

    Appender Detailed explanation

  • <appender> The node itself has two mandatory properties , Namely name and class.name Attribute specifies appender The name of , and class Property specifies the... To be instantiated appender The fully qualified name of the class .<appender> The label may contain 0 or 1 individual <layout> label ,0 Or more <encoder>、<filter> label . The picture below is <appender> The internal structure of :
     

    <configuration>
    
      <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>myApp.log</file>
        
        <encoder>
          <pattern>%date %level [%thread] %logger{10} [%file:%line] %msg%n</pattern>
        </encoder>
      </appender>
    
      <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
          <pattern>%msg%n</pattern>
        </encoder>
      </appender>
    
      <root level="debug">
        <appender-ref ref="FILE" />
        <appender-ref ref="STDOUT" />
      </root>
    </configuration>
    

    The above configuration defines two log outputters FILE and STDOUT, By means of appender-ref Reference name in label , take appenders Attach to root logger .FILE It's the output of debug Level log to name myApp.log The file of ( Automatically created when file does not exist ),STDOUT It's the output of debug Level log to console .

    Be careful : Every appender Each has its own encoder . Encoders are not usually designed to be multiple appenders share . So is the layout . therefore ,logback The configuration file does not provide any syntax means for sharing encoders or layouts .

    By default ,appenders It's cumulative : A logger (logger) Use a appender At the same time, this appender To the root logger (root). therefore , Will be the same appender Attaching to multiple loggers causes the log output to be copied .

  • contextName

  • Each logger is attached to the logger context . By default ,logger The context is called “default”. however , You can configure contextName Set different names . Be careful , Once set , The logger context name cannot be changed . By setting logger The context name can distinguish multiple application logs to the same target . Example :
     

    <configuration>
      <contextName>myAppName</contextName>
      <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
          <pattern>%d %contextName [%t] %level %logger{36} - %msg%n</pattern>
        </encoder>
      </appender>
    
      <root level="debug">
        <appender-ref ref="STDOUT" />
      </root>
    </configuration>
    

  • property
    Variables can be defined once in the configuration file itself , You can also load from external properties files or external resources . For historical reasons , Defining variable XML The element is <property>, But in logback 1.0.7 after , It can also be done through <variable> Defining variables . Example :
  • <configuration>
    
      <property name="USER_HOME" value="/home/sebastien" />
    
      <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>${USER_HOME}/myApp.log</file>
        <encoder>
          <pattern>%msg%n</pattern>
        </encoder>
      </appender>
    
      <root level="debug">
        <appender-ref ref="FILE" />
      </root>
    </configuration>
    

    Define variables internally

  • <configuration>
    
      <property resource="resource1.properties" />
    
      <appender name="FILE" class="ch.qos.logback.core.FileAppender">
         <file>${USER_HOME}/myApp.log</file>
         <encoder>
           <pattern>%msg%n</pattern>
         </encoder>
       </appender>
    
       <root level="debug">
         <appender-ref ref="FILE" />
       </root>
    </configuration>
    

    filter

  • occasionally , We need to be in a specific appender Only specific level logs are output in , You need to use filter. There are many kinds of filters , This is just an introduction LevelFilter and ThresholdFilter

    LevelFilter
    LevelFilter Filter events based on precise level matching . If the level of the event is equal to the configured level , According to onMatch and on Configuration of properties , Filters accept or reject events . Example :

    <configuration>
      <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
          <level>INFO</level>
          <onMatch>ACCEPT</onMatch>
          <onMismatch>DENY</onMismatch>
        </filter>
        <encoder>
          <pattern>
            %-4relative [%thread] %-5level %logger{30} - %msg%n
          </pattern>
        </encoder>
      </appender>
      <root level="DEBUG">
        <appender-ref ref="CONSOLE" />
      </root>
    </configuration>
    

    CONSOLE Only output info Level of logging

  • ThresholdFilter
    Threshold filter filters events below the specified threshold . For events with the same level or exceeding the threshold , When calling it decide() When the method is used , The threshold filter will remain neutral . however , Events below the threshold will be rejected . Example :
<configuration>
  <appender name="CONSOLE"
    class="ch.qos.logback.core.ConsoleAppender">
    <!-- deny all events with a level below INFO, that is TRACE and DEBUG -->
    <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
      <level>INFO</level>
    </filter>
    <encoder>
      <pattern>
        %-4relative [%thread] %-5level %logger{30} - %msg%n
      </pattern>
    </encoder>
  </appender>
  <root level="DEBUG">
    <appender-ref ref="CONSOLE" />
  </root>
</configuration>

 CONSOLE Will be output info、warn、error Level of logging , except debug

Dependency needed :

<!--             Log framework dependency -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-log4j12</artifactId>

                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.2.3</version>
        </dependency>

When the project is started, the corresponding... Will be created in the root directory log Log files .

 

Complete configuration example

<?xml version="1.0" encoding="UTF-8"?>
<!--  The log level is from low to high TRACE < DEBUG < INFO < WARN < ERROR < FATAL, If set to WARN, Less than WARN None of our messages will output  -->
<!-- scan: When this property is set to true when , If the configuration document changes , Will be reloaded , The default value is true -->
<!-- scanPeriod: Set the time interval between changes in the monitoring configuration document , If no time unit is given , The default unit is milliseconds .
                  When scan by true when , This property takes effect . The default time interval is 1 minute . -->
<!-- debug: When this property is set to true when , Will print out logback Internal log information , Real-time view logback Running state . The default value is false. -->
<configuration scan="true" scanPeriod="30 seconds">
    <!--   Color log dependency   -->
    <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" />
    <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" />
    <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />

    <!--   Log file storage address ,  adopt application The configuration file was passed in   -->
        <springProperty scope="context" name="LOG_PATH" source="logback.logDir" />
    <!-- Define the storage address of the log file   Stay away  LogBack  The relative path is used in the configuration of -->
    <property name="LOG_PATH" value="./logs"/>

    <!--   Console color log format   -->
    <property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}" />
    <!--   Log file log format   -->
    <property name="FILE_LOG_PATTERN" value="${FILE_LOG_PATTERN:-%d{${LOG_DATEFORMAT_PATTERN:-yyyy-MM-dd HH:mm:ss.SSS}} ${LOG_LEVEL_PATTERN:-%5p} ${PID:- } --- [%15t] %-40.40logger{39} : %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}" />


    <!--  Console output  -->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>UTF-8</charset>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>


    <!--  Generate log files by day and size  -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <!-- The filename of the log file output -->
            <FileNamePattern>${LOG_PATH}/my-blog-site.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
            <!-- Maximum log file size -->
            <maxFileSize>100MB</maxFileSize>
            <!-- Log file retention days -->
            <maxHistory>30</maxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <pattern>${FILE_LOG_PATTERN}</pattern>
            <charset>UTF-8</charset>
        </encoder>
        <!--  Filter level ,
             If you want to generate log files by classification ( Divide into debug、info、error Wait for three log files ,  Each file only records its own level of logs ),
            1.  Just put this  <appender>  Copy three points and change it  FileNamePattern  and  name.
            2.  hold  <filter>  Remove the comment and change it  level  That's all right. 
        -->
        <!--        <filter class="ch.qos.logback.classic.filter.LevelFilter">-->
        <!--            <level>info</level>-->
        <!--            <onMatch>ACCEPT</onMatch>-->
        <!--            <onMismatch>DENY</onMismatch>-->
        <!--        </filter>-->
    </appender>


    <!--  Log output level 
         If you use springProfile,  It needs to be in application Passed in configuration file  spring.profiles.active=dev  To specify the environment ,
         It can also be removed directly  <springProfile>  This tag or comment it out as a whole 
     -->
    <springProfile name="dev,prod">
        <logger name="org.springframework" level="INFO" additivity="false">
            <appender-ref ref="CONSOLE"/>
            <appender-ref ref="FILE"/>
        </logger>
        <logger name="com.netflix" level="INFO" additivity="false">
            <appender-ref ref="CONSOLE"/>
            <appender-ref ref="FILE"/>
        </logger>
        <logger name="com.pro.test" level="DEBUG" additivity="false">
            <appender-ref ref="CONSOLE"/>
            <appender-ref ref="FILE"/>
        </logger>
        <logger name="java.sql" level="DEBUG" additivity="false">
            <appender-ref ref="CONSOLE"/>
            <appender-ref ref="FILE"/>
        </logger>
        <!-- The path of the project package -->
        <logger name="com.pro" level="DEBUG,INFO" additivity="false">
            <appender-ref ref="CONSOLE"/>
            <appender-ref ref="FILE"/>
        </logger>
    </springProfile>

    <root level="INFO">
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="FILE" />
    </root>
</configuration>

原网站

版权声明
本文为[Mr_ Jin.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206102340229996.html