Spring Boot uses Commons Logging for all internal logging, but leaves the underlying log implementation open. Default configurations are provided for Java Util Logging,Log4J, Log4J2 and Logback. In each case loggers are pre-configured to use console output with optional file output also available.
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.
![]() |
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:
2014-03-05 10:57:51.112 INFO 45469 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.52 2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1358 ms 2014-03-05 10:57:51.698 INFO 45469 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 2014-03-05 10:57:51.702 INFO 45469 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
The following items are output:
- Date and Time — Millisecond precision and easily sortable.
- Log Level —
ERROR
,WARN
,INFO
,DEBUG
orTRACE
. - Process ID.
- A
---
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.
![]() |
Logback does not have a |
The default log configuration will echo messages to the console as they are written. By default ERROR
, WARN
and INFO
level messages are logged. You can also enable a “debug” mode by starting your application with a --debug
flag.
$ java -jar myapp.jar --debug
![]() |
you can also specify |
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 DEBUG
level.
If your terminal supports ANSI, color output will be used to aid readability. You can set spring.output.ansi.enabled
to a supported value to override the auto detection.
Color coding is configured using the %clr
conversion word. In its simplest form the converter will color the output according to the log level, for example:
%clr(%5p)
The mapping of log level to a color is as follows:
Level | Color |
---|---|
|
Red |
|
Red |
|
Yellow |
|
Green |
|
Green |
|
Green |
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:
%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow}
The following colors and styles are supported:
blue
cyan
faint
green
magenta
red
yellow
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 logging.file
orlogging.path
property (for example in your application.properties
).
The following table shows how the logging.*
properties can be used together:
Table 26.1. Logging properties
logging.file |
logging.path |
Example | Description |
---|---|---|---|
(none) |
(none) |
Console only logging. |
|
Specific file |
(none) |
|
Writes to the specified log file. Names can be an exact location or relative to the current directory. |
(none) |
Specific directory |
|
Writes |
Log files will rotate when they reach 10 Mb and as with console output, ERROR
, WARN
and INFO
level messages are logged by default.
![]() |
The logging system is initialized early in the application lifecycle and as such logging properties will not be found in property files loaded via |
![]() |
Logging properties are independent of the actual logging infrastructure. As a result, specific configuration keys (such as |
All the supported logging systems can have the logger levels set in the Spring Environment
(so for example in application.properties
) using ‘logging.level.*=LEVEL’ where ‘LEVEL’ is one of TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF. The root
logger can be configured using logging.level.root
. Exampleapplication.properties
:
logging.level.root=WARN
logging.level.org.springframework.web=DEBUG logging.level.org.hibernate=ERROR
![]() |
By default Spring Boot remaps Thymeleaf |
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 Environment
property logging.config
.
![]() |
Since logging is initialized before the |
Depending on your logging system, the following files will be loaded:
Logging System | Customization |
---|---|
Logback |
|
Log4j |
|
Log4j2 |
|
JDK (Java Util Logging) |
|
![]() |
When possible we recommend that you use the |
![]() |
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 Environment
to System properties:
Spring Environment | System Property | Comments |
---|---|---|
|
|
The conversion word that’s used when logging exceptions. |
|
|
Used in default log configuration if defined. |
|
|
Used in default log configuration if defined. |
|
|
The log pattern to use on the console (stdout). (Not supported with JDK logger.) |
|
|
The log pattern to use in a file (if LOG_FILE enabled). (Not supported with JDK logger.) |
|
|
The format to use to render the log level (default |
|
|
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 spring-boot.jar
for examples.
![]() |
If you want to use a placeholder in a logging property, you should use Spring Boot’s syntax and not the syntax of the underlying framework. Notably, if you’re using Logback, you should use |
![]() |
You can add MDC and other ad-hoc content to log lines by overriding only the 2015-09-30 12:30:04.031 user:juergen INFO 22174 --- [ nio-8080-exec-0] demo.Controller Handling authenticated request |
Spring Boot includes a number of extensions to Logback which can help with advanced configuration. You can use these extensions in your logback-spring.xml
configuration file.
![]() |
You cannot use extensions in the standard |
The <springProfile>
tag allows you to optionally include or exclude sections of configuration based on the active Spring profiles. Profile sections are supported anywhere within the <configuration>
element. Use the name
attribute to specify which profile accepts the configuration. Multiple profiles can be specified using a comma-separated list.
<springProfile name="staging"> <!-- configuration to be enabled when the "staging" profile is active --> </springProfile> <springProfile name="dev, staging"> <!-- configuration to be enabled when the "dev" or "staging" profiles are active --> </springProfile> <springProfile name="!production"> <!-- configuration to be enabled when the "production" profile is not active --> </springProfile>
The <springProperty>
tag allows you to surface properties from the Spring Environment
for use within Logback. This can be useful if you want to access values from your application.properties
file in your logback configuration. The tag works in a similar way to Logback’s standard <property>
tag, but rather than specifying a direct value
you specify the source
of the property (from the Environment
). You can use the scope
attribute if you need to store the property somewhere other than inlocal
scope.
<springProperty scope="context" name="fluentHost" source="myapp.fluentd.host"/> <appender name="FLUENT" class="ch.qos.logback.more.appenders.DataFluentAppender"> <remoteHost>${fluentHost}</remoteHost> ... </appender>
![]() |
The |
鏈接:https://zhuanlan.zhihu.com/p/19958535
來源:知乎
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
基於Spring Boot的應用,程序的入口是SpringApplication類。通過@EnableAutoConfiguration 開啟Spring Boot的自動配置功能。這個是Spring Boot核心價值之一。我們首先要搞清楚的應該是Spring Boot如何自動的配置所有的特性以及如何定制自動化配置過程。這里列出幾個在官方參考文檔中和自動化配置相關的鏈接。
23. Externalized Configuration
36. Developing auto-configuration and using conditions
62.1. Troubleshoot auto-configuration
63. Properties & configuration
如何閱讀自動化配置相關源代碼
通過閱讀以上參考資料,大致可以搞清楚Spring Boot自動化配置的過程需要遵循的方向。但是,閱讀源代碼是了解Spring Boot的自動配置機制的最佳選擇。源代碼鏈接:spring-projects/spring-boot · GitHub。整個項目使用Maven進行管理,直接導入即可。注意不要導入太多的Maven項目,我們的目的是通過閱讀代碼來加深Spring Boot的理解,只需要'spring-boot', 'spring-boot-actuator' 和 'spring-boot-autoconfigure'。
Spring Boot 自動化配置相關源代碼閱讀起來並不困難,在官方文檔中也有一些提示。在讀完官方文檔的基礎上,才能開始閱讀源碼。我把目前了解到的關鍵類列一下。
另外,補充說明一點,本系列文章均基於 Spring Boot 1.2.1.RELEASE 版本。
- SpringApplication (Spring Boot Docs 1.2.1.RELEASE API)
- ConfigFileApplicationListener (Spring Boot Docs 1.2.1.RELEASE API)
Spring Boot通過實現各種ApplicationListener進行實際的配置工作,配置框架是使用Environment 和 PropertySource相關的類。幾點注意事項:
- Spring Boot支持從多個地方加載配置,比如命令行、系統環境變量、JNDI等,因此配置項的語法支持所謂的RelaxedEnvironment。在源碼中,通過查找 Relaxed開頭的類,比如RelaxedPropertyResolver,可以了解到相關的使用情況
- SpringBoot同時支持YAML和Properties格式的配置文件,雖然並不禁止混合使用,但是加載順序是不確定的。
日志框架配置文件位置'logging.config'的一個坑
在Spring Boot 1.2.1中,對於日志框架本身的配置文件位置是通過'logging.config'進行設置的。下面是LoggingApplicationListener的代碼片段:
private void initializeSystem(ConfigurableEnvironment environment, LoggingSystem system) { LogFile logFile = LogFile.get(environment); String logConfig = environment.getProperty(CONFIG_PROPERTY); if (StringUtils.hasLength(logConfig)) { try { //碼農公社:校驗logConfig是否可訪問 ResourceUtils.getURL(logConfig).openStream().close(); system.initialize(logConfig, logFile); } catch (Exception ex) { this.logger.warn("Logging environment value '" + logConfig + "' cannot be opened and will be ignored " + "(using default location instead)"); system.initialize(null, logFile); } } else { system.initialize(null, logFile); } }
關鍵是這一行代碼:
ResourceUtils.getURL(logConfig).openStream().close();
public static URL getURL(String resourceLocation) throws FileNotFoundException { Assert.notNull(resourceLocation, "Resource location must not be null"); if (resourceLocation.startsWith(CLASSPATH_URL_PREFIX)) { String path = resourceLocation.substring(CLASSPATH_URL_PREFIX.length()); ClassLoader cl = ClassUtils.getDefaultClassLoader(); URL url = (cl != null ? cl.getResource(path) : ClassLoader.getSystemResource(path)); if (url == null) { String description = "class path resource [" + path + "]"; throw new FileNotFoundException(description + " cannot be resolved to URL because it does not exist"); } return url; } try { // try URL // 碼農筆記:logging.config必須使用真實的文件路徑,不能是合法的URL語法 return new URL(resourceLocation); } catch (MalformedURLException ex) { // no URL -> treat as file path try { return new File(resourceLocation).toURI().toURL(); } catch (MalformedURLException ex2) { throw new FileNotFoundException("Resource location [" + resourceLocation + "] is neither a URL not a well-formed file path"); } } }
從上面的代碼可得知,'logging.config'如果指定的是文件系統位置,必須直接寫文件路徑,不能加"file:/"前綴。 從而讓 "new URL"拋出MalformedURLException,ResourceUtils.getURL才能返回一個正確的文件URL。
'logging.config'的寫法文檔中沒有明確的說明,因此我一開始誤以為都必須加前綴如classpath: 或者 file:。
https://zhuanlan.zhihu.com/p/19958535