閱讀185 返回首頁    go 阿裏雲 go 技術社區[雲棲]


SpringBoot開發案例之整合日誌管理

有一種力量無人能抵擋,它永不言敗生來倔強。有一種理想照亮了迷茫,在那寫滿榮耀的地方。

00

概述

參考文檔:Logging

這裏順便引用以下部分原文,當然看不明白也沒關係,我們有有道翻譯,如果翻譯的不準確,後麵會提供詳細配置分享給大家。

Spring Boot uses Commons Logging for all internal logging, but leaves the underlying log implementation open. Default configurations are provided for Java Util Logging, Log4J2 and Logback. In each case loggers are pre-configured to use console output with optional file output also available.
By default, If you use the ‘Starters’, Logback will be used for logging. Appropriate Logback routing is also included to ensure that dependent libraries that use Java Util Logging, Commons Logging, Log4J or SLF4J will all work correctly.

使用

pom.xml相關配置就不跟大家在這裏扯了,依賴自行添加。

Console output

配置日誌的相關參數也隻需要寫在 application.properties或者application.yml中就可以了,當然,這僅僅是基礎的配置。

#官方文檔中有提到, SpringBoot 的 Logging 配置的級別有7個:TRACE , DEBUG , INFO , WARN , ERROR , FATAL , OFF
#root日誌以INFO級別輸出
logging.level.root=INFO
#springframework.web日誌以WARN級別輸出
logging.level.org.springframework.web=WARN
#hibernate日誌以ERROR級別輸出
logging.level.org.hibernate=ERROR

加入以上配置後,我們啟動項目,就可以在控製台打印Log信息了。

但是,在生產環境中,日誌往往要以文件形式存放到服務器,下麵介紹一下spring-boot日誌的文件輸出方式。

File output

logging.file=spring_boot.log
logging.pattern.console=%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n
logging.pattern.file=%d{yyyy/MM/dd-HH:mm} [%thread] %-5level %logger- %msg%n

配置完成以後,我們再次啟動項目,這時候會在根目錄下生成一個spring_boot.log日誌文件。

但是,經曆過項目上線的小夥伴,其實這樣配置遠遠達不到生產要求。比如,區分普通日誌和錯誤日誌,按照日期存儲日誌,配置單個日誌文件最大容量,刪除多少天之前的文件等等!下麵與大家分享一款更高級的配置。

Custom log configuration

Depending on your logging system, the following files will be loaded:

Logback:logback-spring.xml, logback-spring.groovy, logback.xml or logback.groovy

Log4j2:log4j2-spring.xml or log4j2.xml

JDK (Java Util Logging):logging.properties

spring-boot日誌管理支持Logback,Log4j2以及Log4j,根據以上說明,我們可以定義文件命名。

下麵我們使用Logback的指定配置文件實現更高級的日誌配置。

logback-spring.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!-- scan 配置文件如果發生改變,將會被重新加載  scanPeriod 檢測間隔時間-->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
    <contextName>spring-boot-log</contextName>
    <include resource="org/springframework/boot/logging/logback/base.xml"/>
    <!-- 普通日誌 -->
    <appender name="INFO_FILE" >
        <file>log/spring-boot-log-info.log</file>
        <!-- 循環政策:基於時間創建日誌文件 -->
        <rollingPolicy >
             <!-- 日誌命名:單個文件大於128MB 按照時間+自增i 生成log文件 -->
            <fileNamePattern>log/spring-boot-log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy >
                <maxFileSize>128MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <!-- 最大保存時間:30天-->
            <maxHistory>30</maxHistory>
        </rollingPolicy>
        <append>true</append>
        <encoder >
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern>
            <charset>utf-8</charset>
        </encoder>
        <filter >
            <level>info</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
     <!-- 錯誤日誌 -->
    <appender name="ERROR_FILE" >
        <file>log/spring-boot-log-error.log</file>
        <!-- 循環政策:基於時間創建日誌文件 -->
        <rollingPolicy >
            <!-- 日誌命名:單個文件大於2MB 按照時間+自增i 生成log文件 -->
            <fileNamePattern>log/spring-boot-log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy >
                <maxFileSize>2MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <!-- 最大保存時間:180天-->
            <maxHistory>180</maxHistory>
        </rollingPolicy>
        <append>true</append>
        <!-- 日誌格式 -->
        <encoder >
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern>
            <charset>utf-8</charset>
        </encoder>
        <!-- 日誌級別過濾器 -->
        <filter >
             <!-- 過濾的級別 -->
             <level>ERROR</level>
             <!-- 匹配時的操作:接收(記錄) -->
             <onMatch>ACCEPT</onMatch>
             <!-- 不匹配時的操作:拒絕(不記錄) -->
             <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
    <!-- 控製台 -->
    <appender name="STDOUT" >
        <!-- 日誌格式 -->
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n</pattern>
            <charset>utf-8</charset>
        </encoder>
        <!--此日誌appender是為開發使用,隻配置最底級別,控製台輸出的日誌級別是大於或等於此級別的日誌信息-->
        <filter >
            <level>INFO</level>
        </filter>
    </appender>
    <!-- additivity 避免執行2次 -->
    <logger name="com.itstyle"  level="INFO"  additivity="false">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="INFO_FILE"/>
        <appender-ref ref="ERROR_FILE"/>
    </logger>
    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="INFO_FILE" />
        <appender-ref ref="ERROR_FILE" />
    </root>
</configuration>

如果我們使用了 Logback 的指定配置文件的話,那麼application.properties 中的配置可以取消了。

測試

配置完成後,我們做一個測試,為了測試方便把info和error日誌容量maxFileSize都改為2MB。

然後啟動程序:

/**
 * 創建者  https://blog.52itstyle.com
 * 創建時間 2017年7月24日
 */
@EnableAutoConfiguration
public class Application  {
    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(Application.class, args);
          while(true){
            logger.info("普通日誌");
            logger.error("錯誤日誌");
          }
    }
}

執行一段時間,如果在項目路徑下生成以下日誌文件說明配置成功。

123

代碼:https://git.oschina.net/52itstyle/spring-boot-log

作者: 小柒

出處: https://blog.52itstyle.com

本文版權歸作者和雲棲社區所有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁麵明顯位置給出, 如有問題, 可郵件(345849402@qq.com)谘詢。

最後更新:2017-08-13 22:41:58

  上一篇:go  網絡安全保衛戰號角吹響
  下一篇:go  貸款、天使投資(風控助手)業務數據庫設計 - 阿裏雲RDS PostgreSQL, HybridDB for PostgreSQL最佳實踐