1. 程式人生 > >11、Logback日誌框架介紹和SpringBoot整合實戰 2節課

11、Logback日誌框架介紹和SpringBoot整合實戰 2節課

1、新日誌框架LogBack介紹
     簡介:日誌介紹和新日誌框架Logback講解

    1.常用處理java的日誌元件 slf4j,log4j,logback,common-logging 等
    
     2、logback介紹:基於Log4j基礎上大量改良,不能單獨使用,推薦配合日誌框架SLF4J來使用
         logback當前分成三個模組:logback-core,logback-classic和logback-access;
         logback-core是其它兩個模組的基礎模組

    3、Logback的核心物件:
         Logger:日誌記錄器
         Appender:指定日誌輸出的目的地,目的地可以是控制檯,檔案
         Layout:日誌佈局 格式化日誌資訊的輸出

       
     4、日誌級別:DEBUG < INFO < WARN < ERROR

        ===========log4j示例===========       
          ### 設定###
         log4j.rootLogger = debug,stdout,D,E

        ### 輸出資訊到控制擡 ###
         log4j.appender.stdout = org.apache.log4j.ConsoleAppender
         log4j.appender.stdout.Target = System.out
         log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
         log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

        ### 輸出DEBUG 級別以上的日誌到=D://logs/error.log ###
         log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
         log4j.appender.D.File = D://logs/log.log
         log4j.appender.D.Append = true
         log4j.appender.D.Threshold = DEBUG
         log4j.appender.D.layout = org.apache.log4j.PatternLayout
         log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

        ### 輸出ERROR 級別以上的日誌到=D://logs/error.log ###
         log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
         log4j.appender.E.File =E://logs/error.log
         log4j.appender.E.Append = true
         log4j.appender.E.Threshold = ERROR
         log4j.appender.E.layout = org.apache.log4j.PatternLayout
         log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

        ===========logback============
    
     4、Log4j日誌轉換為logback線上工具(支援log4j.properties轉換為logback.xml,不支援 log4j.xml轉換為logback.xml)
      https://logback.qos.ch/translator/

2、SpringBoot2.x日誌講解和自定義Logback配置實戰
     簡介:講解SpringBoot2.x整合Logback配置實戰

        1、官網介紹:https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-logging

  日誌節選:

  26.1 Log Format

The default log output from Spring Boot resembles the following example:

2014-03-05 10:57:51.112  INFO 45469 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/7.0.52
2014-03-05 10:57:51.253  INFO 45469 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2014-03-05 10:57:51.253  INFO 45469 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1358 ms
2014-03-05 10:57:51.698  INFO 45469 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2014-03-05 10:57:51.702  INFO 45469 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]

The following items are output:

  • Date and Time: Millisecond precision and easily sortable.
  • Log Level: ERRORWARNINFODEBUG, or TRACE.
  • Process ID.
  • --- separator to distinguish the start of actual log messages.
  • Thread name: Enclosed in square brackets (may be truncated for console output).
  • Logger name: This is usually the source class name (often abbreviated).
  • The log message.

           各個元件案例:https://logback.qos.ch/manual/index.html
        
         2、分析SpringBoot啟動日誌
             1)預設情況下,Spring Boot將日誌輸出到控制檯

        3、整合Logback實戰
             1)建立 日誌檔案logback-spring.xml,官方推薦 -spring.xml結尾
                 預設載入載入配置順序 logback-spring.xml, logback-spring.groovy, logback.xml, or logback.groovy
            
             註釋:
                 <configuration> 子節點
                 <appender></appender>                      
                 <logger></logger>
                 <root></root>(要加在最後)    

  配置檔案程式碼:

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <configuration>
 3 
 4     <appender name="consoleApp" class="ch.qos.logback.core.ConsoleAppender">
 5         <layout class="ch.qos.logback.classic.PatternLayout">
 6             <pattern>
 7                 %date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method:%L -%msg%n
 8             </pattern>
 9         </layout>
10     </appender>
11 
12     <appender name="fileInfoApp" class="ch.qos.logback.core.rolling.RollingFileAppender">
13         <filter class="ch.qos.logback.classic.filter.LevelFilter">
14             <level>ERROR</level>
15             <onMatch>DENY</onMatch>
16             <onMismatch>ACCEPT</onMismatch>
17         </filter>
18         <encoder>
19             <pattern>
20                 %date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method:%L -%msg%n
21             </pattern>
22         </encoder>
23         <!-- 滾動策略 -->
24         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
25             <!-- 路徑 -->
26             <fileNamePattern>app_log/log/app.info.%d.log</fileNamePattern>
27         </rollingPolicy>
28     </appender>
29 
30     <appender name="fileErrorApp"
31         class="ch.qos.logback.core.rolling.RollingFileAppender">
32         <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
33             <level>ERROR</level>
34         </filter>
35         <encoder>
36             <pattern>
37                 %date{yyyy-MM-dd HH:mm:ss.SSS} %-5level[%thread]%logger{56}.%method:%L -%msg%n
38             </pattern>
39         </encoder>
40 
41         <!-- 設定滾動策略 -->
42         <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
43             <!-- 路徑 -->
44             <fileNamePattern>app_log/log/app.err.%d.log</fileNamePattern>
45 
46             <!-- 控制保留的歸檔檔案的最大數量,超出數量就刪除舊檔案,假設設定每個月滾動, 且<maxHistory> 是1,則只儲存最近1個月的檔案,刪除之前的舊檔案 -->
47             <MaxHistory>1</MaxHistory>
48 
49         </rollingPolicy>
50     </appender>
51 
52     <!-- 控制總的輸出級別 -->
53     <root level="INFO">
54         <appender-ref ref="consoleApp" />
55         <appender-ref ref="fileInfoApp" />
56         <appender-ref ref="fileErrorApp" />
57     </root>
58 </configuration>

設定完成後會自動建立資料夾