天天看點

Spring Boot 探索系列 - 自動化配置篇

26. Logging

Part IV. Spring Boot features

By default, If you use the ‘Starter POMs’, 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.

Spring Boot 探索系列 - 自動化配置篇

There are a lot of logging frameworks available for Java. Don’t worry if the above list seems confusing. Generally you won’t need to change your logging dependencies and the Spring Boot defaults will work just fine.

The default log output from Spring Boot looks like this:

The following items are output:

Date and Time — Millisecond precision and easily sortable.

Log Level — <code>ERROR</code>, <code>WARN</code>, <code>INFO</code>, <code>DEBUG</code> or <code>TRACE</code>.

Process ID.

A <code>---</code> separator to distinguish the start of actual log messages.

Thread name — Enclosed in square brackets (may be truncated for console output).

Logger name — This is usually the source class name (often abbreviated).

The log message.

Spring Boot 探索系列 - 自動化配置篇

Logback does not have a <code>FATAL</code> level (it is mapped to <code>ERROR</code>)

The default log configuration will echo messages to the console as they are written. By default <code>ERROR</code>, <code>WARN</code> and <code>INFO</code> level messages are logged. You can also enable a “debug” mode by starting your application with a <code>--debug</code> flag.

Spring Boot 探索系列 - 自動化配置篇

you can also specify <code>debug=true</code> in your <code>application.properties</code>.

When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate and Spring) are configured to output more information. Enabling the debug mode does not configure your application log all messages with <code>DEBUG</code> level.

Color coding is configured using the <code>%clr</code> conversion word. In its simplest form the converter will color the output according to the log level, for example:

The mapping of log level to a color is as follows:

Level

Color

<code>FATAL</code>

Red

<code>ERROR</code>

<code>WARN</code>

Yellow

<code>INFO</code>

Green

<code>DEBUG</code>

<code>TRACE</code>

Alternatively, you can specify the color or style that should be used by providing it as an option to the conversion. For example, to make the text yellow:

The following colors and styles are supported:

<code>blue</code>

<code>cyan</code>

<code>faint</code>

<code>green</code>

<code>magenta</code>

<code>red</code>

<code>yellow</code>

By default, Spring Boot will only log to the console and will not write log files. If you want to write log files in addition to the console output you need to set a <code>logging.file</code> or<code>logging.path</code> property (for example in your <code>application.properties</code>).

The following table shows how the <code>logging.*</code> properties can be used together:

<a href="http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html#d0e4668"></a>

Table 26.1. Logging properties

<code>logging.file</code>

<code>logging.path</code>

Example

Description

(none)

Console only logging.

Specific file

<code>my.log</code>

Writes to the specified log file. Names can be an exact location or relative to the current directory.

Specific directory

<code>/var/log</code>

Writes <code>spring.log</code> to the specified directory. Names can be an exact location or relative to the current directory.

Log files will rotate when they reach 10 Mb and as with console output, <code>ERROR</code>, <code>WARN</code> and <code>INFO</code> level messages are logged by default.

Spring Boot 探索系列 - 自動化配置篇

The logging system is initialized early in the application lifecycle and as such logging properties will not be found in property files loaded via <code>@PropertySource</code>annotations.

Spring Boot 探索系列 - 自動化配置篇

Logging properties are independent of the actual logging infrastructure. As a result, specific configuration keys (such as <code>logback.configurationFile</code> for Logback) are not managed by spring Boot.

All the supported logging systems can have the logger levels set in the Spring <code>Environment</code> (so for example in <code>application.properties</code>) using ‘logging.level.*=LEVEL’ where ‘LEVEL’ is one of TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF. The <code>root</code> logger can be configured using <code>logging.level.root</code>. Example<code>application.properties</code>:

Spring Boot 探索系列 - 自動化配置篇

The various logging systems can be activated by including the appropriate libraries on the classpath, and further customized by providing a suitable configuration file in the root of the classpath, or in a location specified by the Spring <code>Environment</code> property <code>logging.config</code>.

Spring Boot 探索系列 - 自動化配置篇

Since logging is initialized before the <code>ApplicationContext</code> is created, it isn’t possible to control logging from <code>@PropertySources</code> in Spring<code>@Configuration</code> files. System properties and the conventional Spring Boot external configuration files work just fine.)

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

Logging System

Customization

Logback

<code>logback-spring.xml</code>, <code>logback-spring.groovy</code>, <code>logback.xml</code> or <code>logback.groovy</code>

Log4j

<code>log4j-spring.properties</code>, <code>log4j-spring.xml</code>, <code>log4j.properties</code> or <code>log4j.xml</code>

Log4j2

<code>log4j2-spring.xml</code> or <code>log4j2.xml</code>

JDK (Java Util Logging)

<code>logging.properties</code>

Spring Boot 探索系列 - 自動化配置篇

When possible we recommend that you use the <code>-spring</code> variants for your logging configuration (for example <code>logback-spring.xml</code> rather than<code>logback.xml</code>). If you use standard configuration locations, Spring cannot completely control log initialization.

Spring Boot 探索系列 - 自動化配置篇

There are known classloading issues with Java Util Logging that cause problems when running from an ‘executable jar’. We recommend that you avoid it if at all possible.

To help with the customization some other properties are transferred from the Spring <code>Environment</code> to System properties:

Spring Environment

System Property

Comments

<code>logging.exception-conversion-word</code>

<code>LOG_EXCEPTION_CONVERSION_WORD</code>

The conversion word that’s used when logging exceptions.

<code>LOG_FILE</code>

Used in default log configuration if defined.

<code>LOG_PATH</code>

<code>logging.pattern.console</code>

<code>CONSOLE_LOG_PATTERN</code>

The log pattern to use on the console (stdout). (Not supported with JDK logger.)

<code>logging.pattern.file</code>

<code>FILE_LOG_PATTERN</code>

The log pattern to use in a file (if LOG_FILE enabled). (Not supported with JDK logger.)

<code>logging.pattern.level</code>

<code>LOG_LEVEL_PATTERN</code>

The format to use to render the log level (default <code>%5p</code>). (The<code>logging.pattern.level</code> form is only supported by Logback.)

<code>PID</code>

The current process ID (discovered if possible and when not already defined as an OS environment variable).

All the logging systems supported can consult System properties when parsing their configuration files. See the default configurations in <code>spring-boot.jar</code> for examples.

Spring Boot 探索系列 - 自動化配置篇
Spring Boot 探索系列 - 自動化配置篇

You can add MDC and other ad-hoc content to log lines by overriding only the <code>LOG_LEVEL_PATTERN</code> (or <code>logging.pattern.level</code> with Logback). For example, if you use <code>logging.pattern.level=user:%X{user} %5p</code> then the default log format will contain an MDC entry for "user" if it exists, e.g.

Spring Boot includes a number of extensions to Logback which can help with advanced configuration. You can use these extensions in your <code>logback-spring.xml</code>configuration file.

Spring Boot 探索系列 - 自動化配置篇

You cannot use extensions in the standard <code>logback.xml</code> configuration file since it’s loaded too early. You need to either use <code>logback-spring.xml</code> or define a <code>logging.config</code> property.

The <code>&lt;springProfile&gt;</code> tag allows you to optionally include or exclude sections of configuration based on the active Spring profiles. Profile sections are supported anywhere within the <code>&lt;configuration&gt;</code> element. Use the <code>name</code> attribute to specify which profile accepts the configuration. Multiple profiles can be specified using a comma-separated list.

The <code>&lt;springProperty&gt;</code> tag allows you to surface properties from the Spring <code>Environment</code> for use within Logback. This can be useful if you want to access values from your <code>application.properties</code> file in your logback configuration. The tag works in a similar way to Logback’s standard <code>&lt;property&gt;</code> tag, but rather than specifying a direct <code>value</code> you specify the <code>source</code> of the property (from the <code>Environment</code>). You can use the <code>scope</code> attribute if you need to store the property somewhere other than in<code>local</code> scope.

Spring Boot 探索系列 - 自動化配置篇

The <code>RelaxedPropertyResolver</code> is used to access <code>Environment</code> properties. If specify the <code>source</code> in dashed notation (<code>my-property-name</code>) all the relaxed variations will be tried (<code>myPropertyName</code>, <code>MY_PROPERTY_NAME</code> etc).

http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

作者:孫立偉

連結:https://zhuanlan.zhihu.com/p/19958535

來源:知乎

著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。

<a href="https://link.zhihu.com/?target=http%3A//docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html" target="_blank">23. Externalized Configuration</a> <a href="https://link.zhihu.com/?target=http%3A//docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-auto-configuration.html" target="_blank">36. Developing auto-configuration and using conditions</a> <a href="https://link.zhihu.com/?target=http%3A//docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-boot-application.html%23howto-troubleshoot-auto-configuration" target="_blank">62.1. Troubleshoot auto-configuration</a> <a href="https://link.zhihu.com/?target=http%3A//docs.spring.io/spring-boot/docs/current/reference/html/howto-properties-and-configuration.html" target="_blank">63. Properties &amp; configuration</a> <a href="https://link.zhihu.com/?target=http%3A//docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html" target="_blank">Appendix A. Common application properties</a> <a href="https://link.zhihu.com/?target=http%3A//docs.spring.io/spring-boot/docs/current/reference/html/auto-configuration-classes.html" target="_blank">Appendix C. Auto-configuration classes</a>

Spring Boot 自動化配置相關源代碼閱讀起來并不困難,在官方文檔中也有一些提示。在讀完官方文檔的基礎上,才能開始閱讀源碼。我把目前了解到的關鍵類列一下。

另外,補充說明一點,本系列文章均基于 Spring Boot 1.2.1.RELEASE 版本。

<a href="https://link.zhihu.com/?target=http%3A//docs.spring.io/autorepo/docs/spring-boot/1.2.1.RELEASE/api/org/springframework/boot/SpringApplication.html" target="_blank">SpringApplication (Spring Boot Docs 1.2.1.RELEASE API)</a>

<a href="https://link.zhihu.com/?target=http%3A//docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/context/config/ConfigFileApplicationListener.html" target="_blank">ConfigFileApplicationListener (Spring Boot Docs 1.2.1.RELEASE API)</a>

Spring Boot通過實作各種ApplicationListener進行實際的配置工作,配置架構是使用Environment 和 PropertySource相關的類。幾點注意事項:

Spring Boot支援從多個地方加載配置,比如指令行、系統環境變量、JNDI等,是以配置項的文法支援所謂的RelaxedEnvironment。在源碼中,通過查找 Relaxed開頭的類,比如RelaxedPropertyResolver,可以了解到相關的使用情況

SpringBoot同時支援YAML和Properties格式的配置檔案,雖然并不禁止混合使用,但是加載順序是不确定的。

在Spring Boot 1.2.1中,對于日志架構本身的配置檔案位置是通過'logging.config'進行設定的。下面是LoggingApplicationListener的代碼片段:

(知乎專欄不支援對代碼加行号,很不友善啊!)

關鍵是這一行代碼:

得到'logging.config'(即常量 CONFIG_PROPERTY)所配置的值後,LoggingApplicationListener先調用ResourceUtils.geURL().openStream() 校驗指定的位置是否可讀。下面是 ResourceUtils.getURL的源碼:

從上面的代碼可得知,'logging.config'如果指定的是檔案系統位置,必須直接寫檔案路徑,不能加"file:/"字首。 進而讓 "new URL"抛出MalformedURLException,ResourceUtils.getURL才能傳回一個正确的檔案URL。

'logging.config'的寫法文檔中沒有明确的說明,是以我一開始誤以為都必須加字首如classpath: 或者 file:。

https://zhuanlan.zhihu.com/p/19958535