Spring Boot 日誌處理

寫於:2018-05-01 晚 21:00

  • 日誌介紹
  • 默認日誌格式
  • 控制檯輸出,彩色日誌
  • 文件輸出
  • 日誌級別
  • 自定義日誌配置

1. 日誌介紹

官方翻譯:Spring Boot內部日誌系統使用的是Commons Logging,但開放底層的日誌實現。默認爲會Java Util Logging, Log4J, Log4J2和Logback提供配置。每種情況下都會預先配置使用控制檯輸出,也可以使用可選的文件輸出。默認情況下,如果你使用’Starter POMs’,那麼就會使用Logback記錄日誌。爲了確保那些使用Java Util Logging, Commons Logging, Log4J或SLF4J的依賴庫能夠正常工作,正確的Logback路由也被包含進來。

2. 默認日誌格式


2018-05-01 19:49:35.456  INFO 17904 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-05-01 19:49:35.494  INFO 17904 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-01 19:49:35.495  INFO 17904 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-01 19:49:35.535  INFO 17904 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-01 19:49:35.756  INFO 17904 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-05-01 19:49:35.794  INFO 17904 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-05-01 19:49:35.798  INFO 17904 --- [           main] com.yiqixuejava.Example                  : Started Example in 2.647 seconds (JVM running for 4.358)

輸出的節點(items)如下:
1. 日期和時間 - 精確到毫秒,且易於排序
2. 日誌級別 - ERROR, WARN, INFO, DEBUG 或 TRACE
3. Process ID
4. 一個用於區分實際日誌信息開頭的—分隔符
5. 線程名 - 包括在方括號中(控制檯輸出可能會被截斷)
6. 日誌名 - 通常是源class的類名(縮寫)
7. 日誌信息

3. 控制檯輸出,彩色日誌

默認的日誌配置會在寫日誌消息時將它們回顯到控制檯。默認,ERROR, WARN和INFO級別
的消息會被記錄。可以在啓動應用時,通過 –debug 標識開啓控制檯的DEBUG級別日誌記
錄。

例如: java -jar yiqixuejava-log-default.jar --debug

查看結果(將看到自動配置項):
2018-05-01 19:56:36.238  INFO 18416 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-05-01 19:56:36.247 DEBUG 18416 --- [           main] ationConfigEmbeddedWebApplicationContext : Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@c46bcd4]
2018-05-01 19:56:36.263 DEBUG 18416 --- [           main] utoConfigurationReportLoggingInitializer :


=========================
AUTO-CONFIGURATION REPORT
=========================


Positive matches:
-----------------

   DispatcherServletAutoConfiguration matched:
      - @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
      - @ConditionalOnWebApplication (required) found StandardServletEnvironment (OnWebApplicationCondition)

如果你的終端支持ANSI,爲了增加可讀性將會使用彩色的日誌輸出。你可以設
置 spring.output.ansi.enabled 爲一個支持的值來覆蓋自動檢測

默認(嘗試檢測ANSI着色功能是否可用。):
spring.output.ansi.enabled=DETECT
由於我的電腦是支持ANSI,所以是彩色的,和ALWAYS效果一致

可選值(ALWAYS,NEVER)
- ALWAYS:啓用ANSI顏色的輸出。
- NEVER: 禁用ANSI顏色的輸出。
顏色源碼:
    public enum Enabled {

        /**
         * Try to detect whether ANSI coloring capabilities are available. The default
         * value for {@link AnsiOutput}.
         */
        DETECT,

        /**
         * Enable ANSI-colored output.
         */
        ALWAYS,

        /**
         * Disable ANSI-colored output.
         */
        NEVER

    }

4. 文件輸出

默認情況下,Spring Boot只會將日誌記錄到控制檯而不會寫進日誌文件。如果除了輸出到控
制臺你還想寫入到日誌文件,那你需要設置 logging.file 或 logging.path 屬性(例如在你的
application.properties中)。
下表顯示如何組合使用 logging.* :

logging.file ogging.path 示例 描述
只記錄到控制檯
特定的文件 my.log 寫到特定的日誌文件裏,名稱可以是一個確定的位置或相對於當前目錄
特地的位置 /var/log 寫到特定文件夾下的spring.log裏,名稱可以是一個精確的位置或相對於當前目錄

日誌文件每達到10M就會被輪換(分割),和控制檯一樣,默認記錄ERROR, WARN和INFO
級別的信息。

舉例1:

- 配置日誌文件名字
logging.file=my.log

配置文件名字

結論:配置日誌名字,默認生成在當前項目的跟目錄

舉例2:

- 配置日誌文件名字且有路徑
logging.file=E://work//openResources//yiqixuejava//yiqixuejava-log-default//src//main//resources//my.log

配置日誌文件名字且有路徑

結論:配置日誌名字且有路徑,日誌生成在指定目錄

舉例3:

- 配置日誌文件路徑
logging.path=E://work//openResources//yiqixuejava//yiqixuejava-log-default//

配置日誌文件路徑

結論:配置日誌文件路徑,生成在指定目錄下,名字叫spring.log

舉例4:

#配置日誌文件路徑且有文件名字
logging.path=E://work//openResources//yiqixuejava//yiqixuejava-log-default//my.log

配置日誌文件路徑且有文件名字

結論:配置日誌文件路徑且有文件名字,無法生成指定文件名的文件,只能生成spring.log

舉例5:

#配置日誌文件相對目錄
logging.path=.//yiqixuejava-log-default//src//main//resources//

配置日誌文件相對目錄

結論:配置日誌文件相對目錄,可以在相對目錄下生成文件

舉例6:

#配置日誌文件目錄和日誌文件名字
logging.path=.//yiqixuejava-log-default//src//main//resources//
logging.file=my.log

配置日誌文件目錄和日誌文件名字

結論:配置日誌文件目錄和日誌文件名字,只會讓文件名字生效

5.日誌級別

所有支持的日誌系統在Spring的Environment(例如在application.properties裏)都有通
過’logging.level.*=LEVEL’(’LEVEL’是TRACE, DEBUG, INFO, WARN, ERROR, FATAL,
OFF中的一個)設置的日誌級別

例如:

#配置Spring web的日誌級別爲debug
logging.level.org.springframework.web=debug
結果:

2018-05-01 21:02:43.107 DEBUG 3908 --- [           main] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'applicationEventMulticaster': no URL paths identified
2018-05-01 21:02:43.107 DEBUG 3908 --- [           main] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'servletContext': no URL paths identified
2018-05-01 21:02:43.107 DEBUG 3908 --- [           main] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'contextParameters': no URL paths identified
2018-05-01 21:02:43.108 DEBUG 3908 --- [           main] o.s.w.s.h.BeanNameUrlHandlerMapping      : Rejected bean name 'contextAttributes': no URL paths identified
2018-05-01 21:02:43.121  INFO 3908 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-01 21:02:43.121  INFO 3908 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-01 21:02:43.132 DEBUG 3908 --- [           main] .m.m.a.ExceptionHandlerExceptionResolver : Looking for exception mappings: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4d15107f: startup date [Tue May 01 21:02:41 CST 2018]; root of context hierarchy
2018-05-01 21:02:43.159  INFO 3908 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-01 21:02:43.378  INFO 3908 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-05-01 21:02:43.387 DEBUG 3908 --- [           main] o.s.w.s.resource.ResourceUrlProvider     : Looking for resource handler mappings
2018-05-01 21:02:43.388 DEBUG 3908 --- [           main] o.s.w.s.resource.ResourceUrlProvider     : Found resource handler mapping: URL pattern="/**/favicon.ico", locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/], class path resource []], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@51a8313b]
2018-05-01 21:02:43.388 DEBUG 3908 --- [           main] o.s.w.s.resource.ResourceUrlProvider     : Found resource handler mapping: URL pattern="/webjars/**", locations=[class path resource [META-INF/resources/webjars/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@2a03d65c]
2018-05-01 21:02:43.388 DEBUG 3908 --- [           main] o.s.w.s.resource.ResourceUrlProvider     : Found resource handler mapping: URL pattern="/**", locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@6642dc5a]
2018-05-01 21:02:43.415  INFO 3908 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2018-05-01 21:02:43.416 DEBUG 3908 --- [           main] o.s.w.c.s.StandardServletEnvironment     : Adding PropertySource 'server.ports' with highest search precedence
2018-05-01 21:02:43.419  INFO 3908 --- [           main] com.yiqixuejava.Example                  : Started Example in 2.443 seconds (JVM running for 3.661)

6.自定義日誌配置

通過將適當的庫添加到classpath,可以激活各種日誌系統。然後在classpath的根目錄(root)或
通過Spring Environment的 logging.config 屬性指定的位置提供一個合適的配置文件來達到
進一步的定製(注意由於日誌是在ApplicationContext被創建之前初始化的,所以不可能在
Spring的@Configuration文件中,通過@PropertySources控制日誌。系統屬性和平常的
Spring Boot外部配置文件能正常工作)
根據你的日誌系統,下面的文件會被加載:

日誌系統 定製
Logback logback.xml
Log4j log4j.properties或log4j.xml
Log4j2 log4j2.xml
JDK (Java Util Logging) logging.properties

爲了幫助定製一些其他的屬性,從Spring的Envrionment轉換到系統屬性:

Spring Environment System Property 評價
logging.file LOG_FILE 如果定義,在默認的日誌配置中使用
logging.path LOG_PATH 如果定義,在默認的日誌配置中使用
PID PID 當前的處理進程(process)ID(如果能夠被發現且還沒有作爲操作系統環境變量被定義)

所有支持的日誌系統在解析它們的配置文件時都能查詢系統屬性。具體可以參考spring-
boot.jar中的默認配置。
注:在運行可執行的jar時,Java Util Logging有類加載問題,官網建議你儘可能避免使用它。

本節未完待繼續!
後續章節:自定義日誌文件(logback,log4j)

個人公衆號
個人公衆號

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章