1. 程式人生 > >SpringBoot 中的 slf4j 日誌依賴關係

SpringBoot 中的 slf4j 日誌依賴關係

SpringBoot底層使用的是slf4j+logback來進行日誌記錄

  • 把其他common-logginglog4jjava.util.logging轉換為slf4j

底層依賴關係

關係如何轉化

底層通過偷樑換柱的方法,用jcl、jul、log4j中間轉換包進行轉化

如果要引入其他框架,必須將其中預設日誌依賴剔除

SpringBoot從maven依賴中剔除springframework:spring-core中的common-logging

<dependency>
<groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.20.RELEASE</version> <exclusions> <exclusion> <artifactId>commons-logging</artifactId> <groupId>commons-logging</groupId>
</exclusion> </exclusions> </dependency> 複製程式碼

+++

SpringBoot預設日誌級別為INFO級別

  • 日誌優先順序從小到大順序為:
    • trace<debug<info<warn<error
package com.example.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import
org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class DemoApplicationTests { Logger log = LoggerFactory.getLogger(getClass()); @Test public void contextLoads() { log.trace("trace日誌"); log.debug("debug日誌"); log.info("info日誌"); log.warn("warn日誌"); log.error("error日誌"); } } 複製程式碼
  • 啟動執行,控制檯列印只打印了info及以上級別
2018-11-09 00:13:36.899  INFO 8156 --- [main] com.example.demo.DemoApplicationTests    : info日誌
2018-11-09 00:13:36.900  WARN 8156 --- [main] com.example.demo.DemoApplicationTests    : warn日誌
2018-11-09 00:13:36.900 ERROR 8156 --- [main] com.example.demo.DemoApplicationTests    : error日誌
複製程式碼

日誌基礎配置

# 指定日誌輸入級別
logging.level.com.example.demo=trace 

# 指定日誌輸出位置和日誌檔名
logging.file=./log/log.txt

# 指定日誌輸出路徑,若file和path同時配置,則file生效
# 此配置預設生成檔案為spring.log
#logging.path=./log

# 控制檯日誌輸出格式
# -5表示從左顯示5個字元寬度
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} %highlight(%-5level) %boldYellow(%thread) | %boldGreen(%logger) | %msg%n

# 檔案中輸出的格式
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} = [%thread] = %-5level = %logger{50} - %msg%n
複製程式碼