Spring Boot日誌框架實踐

CodeSheep發表於2019-03-04

概述

Java應用中,日誌一般分為以下5個級別:

  • ERROR 錯誤資訊
  • WARN 警告資訊
  • INFO 一般資訊
  • DEBUG 除錯資訊
  • TRACE 跟蹤資訊

Spring Boot使用Apache的Commons Logging作為內部的日誌框架,其僅僅是一個日誌介面,在實際應用中需要為該介面來指定相應的日誌實現。

SpringBt預設的日誌實現是Java Util Logging,是JDK自帶的日誌包,此外SpringBt當然也支援Log4J、Logback這類很流行的日誌實現。

統一將上面這些日誌實現統稱為日誌框架

下面我們來實踐一下!

注: 本文首發於 My 公眾號 CodeSheep ,可 長按掃描 下面的 小心心 來訂閱 ↓ ↓ ↓

CodeSheep · 程式羊


使用Spring Boot Logging外掛

  • 首先application.properties檔案中加配置:
logging.level.root=INFO
複製程式碼
  • 控制器部分程式碼如下:
package com.hansonwang99.controller;

import com.hansonwang99.K8sresctrlApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/testlogging")
public class LoggingTestController {
    private static Logger logger = LoggerFactory.getLogger(K8sresctrlApplication.class);
    @GetMapping("/hello")
    public String hello() {
        logger.info("test logging...");
        return "hello";
    }
}
複製程式碼
  • 執行結果

執行結果

由於將日誌等級設定為INFO,因此包含INFO及以上級別的日誌資訊都會列印出來

這裡可以看出,很多大部分的INFO日誌均來自於SpringBt框架本身,如果我們想遮蔽它們,可以將日誌級別統一先全部設定為ERROR,這樣框架自身的INFO資訊不會被列印。然後再將應用中特定的包設定為DEBUG級別的日誌,這樣就可以只看到所關心的包中的DEBUG及以上級別的日誌了。

  • 控制特定包的日誌級別

application.yml中改配置

logging:
  level:
    root: error
    com.hansonwang99.controller: debug
複製程式碼

很明顯,將root日誌級別設定為ERROR,然後再將com.hansonwang99.controller包的日誌級別設為DEBUG,此即:即先禁止所有再允許個別的 設定方法

  • 控制器程式碼
package com.hansonwang99.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/testlogging")
public class LoggingTestController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @GetMapping("/hello")
    public String hello() {
        logger.info("test logging...");
        return "hello";
    }
}

複製程式碼
  • 執行結果

執行結果

可見框架自身的INFO級別日誌全部藏匿,而指定包中的日誌按級別順利地列印出來

  • 將日誌輸出到某個檔案中
logging:
  level:
    root: error
    com.hansonwang99.controller: debug
  file: ${user.home}/logs/hello.log
複製程式碼
  • 執行結果

執行結果

執行結果

使用Spring Boot Logging,我們發現雖然日誌已輸出到檔案中,但控制檯中依然會列印一份,發現用org.slf4j.Logger是無法解決這個問題的

v執行結果


整合Log4J日誌框架

  • pom.xml中新增依賴
       <dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<exclusions>
				<exclusion>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-starter-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-log4j2</artifactId>
		</dependency>
複製程式碼
  • 在resources目錄下新增log4j2.xml檔案,內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>

    <appenders>
        <File name="file" fileName="${sys:user.home}/logs/hello2.log">
            <PatternLayout pattern="%d{HH:mm:ss,SSS} %p %c (%L) - %m%n"/>
        </File>
    </appenders>

    <loggers>

        <root level="ERROR">
            <appender-ref ref="file"/>
        </root>
        <logger name="com.hansonwang99.controller" level="DEBUG" />
    </loggers>

</configuration>
複製程式碼
  • 其他程式碼都保持不變

執行程式發現控制檯沒有日誌輸出,而hello2.log檔案中有內容,這符合我們的預期:

執行結果

執行結果

執行結果

而且日誌格式和pattern="%d{HH:mm:ss,SSS} %p %c (%L) - %m%n"格式中定義的相匹配


Log4J更進一步實踐

  • pom.xml配置:
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<exclusions>
				<exclusion>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-starter-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-log4j2</artifactId>
		</dependency>
複製程式碼
  • log4j2.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="warn">
    <properties>

        <Property name="app_name">springboot-web</Property>
        <Property name="log_path">logs/${app_name}</Property>

    </properties>
    <appenders>
        <console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%d][%t][%p][%l] %m%n" />
        </console>

        <RollingFile name="RollingFileInfo" fileName="${log_path}/info.log"
                     filePattern="${log_path}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log.gz">
            <Filters>
                <ThresholdFilter level="INFO" />
                <ThresholdFilter level="WARN" onMatch="DENY"
                                 onMismatch="NEUTRAL" />
            </Filters>
            <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n" />
            <Policies>
                <!-- 歸檔每天的檔案 -->
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
                <!-- 限制單個檔案大小 -->
                <SizeBasedTriggeringPolicy size="2 MB" />
            </Policies>
            <!-- 限制每天檔案個數 -->
            <DefaultRolloverStrategy compressionLevel="0" max="10"/>
        </RollingFile>

        <RollingFile name="RollingFileWarn" fileName="${log_path}/warn.log"
                     filePattern="${log_path}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log.gz">
            <Filters>
                <ThresholdFilter level="WARN" />
                <ThresholdFilter level="ERROR" onMatch="DENY"
                                 onMismatch="NEUTRAL" />
            </Filters>
            <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n" />
            <Policies>
                <!-- 歸檔每天的檔案 -->
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
                <!-- 限制單個檔案大小 -->
                <SizeBasedTriggeringPolicy size="2 MB" />
            </Policies>
            <!-- 限制每天檔案個數 -->
            <DefaultRolloverStrategy compressionLevel="0" max="10"/>
        </RollingFile>

        <RollingFile name="RollingFileError" fileName="${log_path}/error.log"
                     filePattern="${log_path}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log.gz">
            <ThresholdFilter level="ERROR" />
            <PatternLayout pattern="[%d][%t][%p][%c:%L] %m%n" />
            <Policies>
                <!-- 歸檔每天的檔案 -->
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
                <!-- 限制單個檔案大小 -->
                <SizeBasedTriggeringPolicy size="2 MB" />
            </Policies>
            <!-- 限制每天檔案個數 -->
            <DefaultRolloverStrategy compressionLevel="0" max="10"/>
        </RollingFile>

    </appenders>

    <loggers>


        <root level="info">
            <appender-ref ref="Console" />
            <appender-ref ref="RollingFileInfo" />
            <appender-ref ref="RollingFileWarn" />
            <appender-ref ref="RollingFileError" />
        </root>

    </loggers>

</configuration>
複製程式碼
  • 控制器程式碼:
package com.hansonwang99.controller;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/testlogging")
public class LoggingTestController {
    private final Logger logger = LogManager.getLogger(this.getClass());
    @GetMapping("/hello")
    public String hello() {
        for(int i=0;i<10_0000;i++){
            logger.info("info execute index method");
            logger.warn("warn execute index method");
            logger.error("error execute index method");
        }
        return "My First SpringBoot Application";
    }
}

複製程式碼
  • 執行結果

執行結果

執行結果

執行結果

日誌會根據不同的級別儲存在不同的檔案,當日志檔案大小超過2M以後會分多個檔案壓縮儲存,生產環境的日誌檔案大小建議調整為20-50MB。


後記

作者更多的SpringBt實踐文章在此:


如果有興趣,也可以抽點時間看看作者一些關於容器化、微服務化方面的文章:


CodeSheep · 程式羊


相關文章