1. 程式人生 > >spring boot slf4j 配置日誌記錄

spring boot slf4j 配置日誌記錄

在開發中列印內容,使用 System.out.println() 和 Log4j 應當是人人皆知的方法了。

其實在開發中我們不建議使用 System.out 因為大量的使用 System.out 會增加資源的消耗。

而Log4j 更為靈活在效能上也相比 System.out 要高,我們可以配置輸出級別,可以指定多個日誌檔案分別記錄不同的日誌。

       使用 System.out 是在當前執行緒執行的,寫入檔案也是寫入完畢後才繼續執行下面的程式。而使用Log工具不但可以控制日誌是否輸出,怎麼輸出,它的處理機制也是通知寫日誌,繼續執行後面的程式碼不必等日誌寫完。

如非必要,建議大家不要使用控制檯輸出,因為控制檯輸出沒有優先順序會顯得輸出太亂。

       個人推薦使用 SLF4J(Simple Logging Facade For Java)的logback來輸出日誌,其比log4j 要好,因為他效率更高。

       Spring Boot 提供了一套日誌系統,logback是最優先的選擇。

在Spring Boot 中記錄日誌只需兩步: 

1、在 src/main/resources 下面建立logback.xml (根據不同環境來定義不同的日誌輸出,那麼取名為logback-spring.xml 即可)檔案,並按上面講述的進行配置。 

或者使用最簡單的方法在 application 配置檔案中配置。 

2、在Java程式碼中建立例項,並在需要輸出日誌的地方使用。

logback-spring.xml 檔案:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 <?xml version="1.0" encoding="UTF-8"?> <configuration> <include resource="org/springframework/boot/logging/logback/base.xml" /> <logger name="org.springframework.web" level="INFO"/> <logger name="org.springboot.sample" level
="TRACE" /> <springProfile name="dev"> <logger name="org.springboot.sample" level="DEBUG" /> </springProfile> <springProfile name="staging"> <logger name="org.springboot.sample" level="INFO" /> </springProfile> </configuration>

在程式碼中呼叫:

1 2 3 4 import org.slf4j.Logger; import org.slf4j.LoggerFactory; private Logger logger =  LoggerFactory.getLogger(this.getClass());