文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
26. Logging
Spring Boot uses Commons Logging for all internal logging, but leaves the underlying log implementation open. Default configurations are provided for Java Util Logging, Log4J2 and Logback. In each case loggers are pre-configured to use console output with optional file output also available.
Spring Boot所有的内部日志都采用Commons Logging,但开放了底层的日志实现。提供了对Java Util Logging,Log4J2和Logback的默认实现。在每个logger中都预先配置使用控制台作为输出,同时也可用可选的文件输出。
By default, If you use the ‘Starters’, 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.
默认情况下,如果使用Starters
,Logback将作为日志。也要包含恰当的Logback规则来保证依赖库使用Java Util Logging,Commons Logging,Log4J或SLF4J都能正确工作。
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.
在Java中有许多日志框架可用。不必担心上面的列表看起来有点混乱。通常情况下你不需要改变你的日志依赖,Spring Boot默认情况下能很好的工作。
26.1 Log format
The default log output from Spring Boot looks like this:
Spring Boot默认的日志输出看起来如下:
1 | 2014-03-05 10:57:51.112 INFO 45469 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.52 |
The following items are output:
Date and Time — Millisecond precision and easily sortable.
Log Level — ERROR, WARN, INFO, DEBUG or TRACE.
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.
下面的是输出项:
Date and Time — 精确到毫秒且容易排序。
Log级别 — ERROR,WARN,INFO,DEBUG或TRACE。
进程ID。
---
分隔符来区分真正的日志信息的开始。线程名称 — 用方括号包裹(在控制台输出中经常是缩减的)。
Logger名称 — 源类名(经常是简写)。
日志信息。
Logback does not have a FATAL level (it is mapped to ERROR)
Logback没有FATAL级别(它映射到ERROR)。
26.2 Console output
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.
默认的日志配置会将信息输出到控制台。默认情况下会输出ERROR
,WARN
和INFO
级别的信息。你也可以通过--debug
来启动你的应用,从而启用“debug”模式。
1 | $ java -jar myapp.jar --debug |
you can also specify
debug=true
in yourapplication.properties
.
你也可以在
application.properties
指定debug=true
。
When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG
level.
当启用调试模式时,配置选择的核心logger(嵌入式容器,Hibernate和Spring Boot)来输出更多的信息。启动调试模式不会将你的应用配置成输出所有DEBUG
级别的信息。
Alternatively, you can enable a “trace” mode by starting your application with a --trace
flag (or trace=true
in your application.properties
). This will enable trace logging for a selection of core loggers (embedded container, Hibernate schema generation and the whole Spring portfolio).
或者,你可以用--trace
标记(或在application.properties
中添加trace=true
)启动你的应用,从而启用“trace”模式。这将在选择的核心logger中(嵌入式容器,Hibernate模式生成和整个Spring文件夹)启用trace日志。
26.2.1 Color-coded output
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.
如果你的终端支持ANSI,颜色输出可以用来辅助阅读。你可以为spring.output.ansi.enabled
设置一个支持值来覆盖自动检测。
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
转换词来配置。最简单的形式是根据日志级别进行颜色输出,例如:
1 | %clr(%5p) |
The mapping of log level to a color is as follows:
日志级别与颜色的映射如下:
Level | Color |
---|---|
FATAL | Red |
ERROR | Red |
WARN | Yellow |
INFO | Green |
DEBUG | Green |
TRACE | 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:
或者,你可以通过在转换器中提供选项来指定应该试用的颜色或风格。例如,为了使文本显示黄色:
1 | %clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){yellow} |
The following colors and styles are supported:
支持下面的颜色和风格:
- blue
- cyan
- faint
- green
- magenta
- red
- yellow
26.3 File output
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
or logging.path
property (for example in your application.properties
).
默认情况下,Spring Boot只能输出日志到控制台,不会写入日志文件。如果你想除了控制台之外还想写日志文件,你需要设置logging.file
或logging.path
属性(例如,在你的application.properties
)。
The following table shows how the logging.*
properties can be used together:
下表显示了logging.*
属性怎样在一起使用:
Table 26.1. Logging properties
logging.file | logging.path | Example | Description |
---|---|---|---|
(none | (none) | Console only logging. | |
Specific file | (none) | my.log | Writes to the specified log file. Names can be an exact location or relative to the current directory. |
(none) | Specific directory | /var/log | Writes spring.log to the specified directory. Names can be an exact location or relative to the current directory. |
表 26.1. Logging属性
logging.file | logging.path | Example | Description |
---|---|---|---|
(none | (none) | 只输出到控制台 | |
指定文件 | (none) | my.log | 写入指定的日志文件。名字可以是一个绝对位置或相对于当前目录。 |
(none) | Specific directory | /var/log | 写spring.log 到一个指定的目录。名字可以是一个绝对位置或相对于当前目录。 |
Log files will rotate when they reach 10 MB and as with console output, ERROR
, WARN
and INFO
level messages are logged by default.
当日志文件达到10M时日志文件将循环,至于控制台输出,默认情况下只输出ERROR
,WARN
和INFO
级别的信息。
The logging system is initialized early in the application lifecycle and as such logging properties will not be found in property files loaded via
@PropertySource
annotations.
日志系统在应用程序的生命周期早期进行初始化,同样地,通过
@PropertySource
注解加载的属性文件中将不会发现日志属性。
Logging properties are independent of the actual logging infrastructure. As a result, specific configuration keys (such as
logback.configurationFile
for Logback) are not managed by spring Boot.
日志属性独立于真正的日志基础架构之外。因此,Spring Boot不管理特定的配置主键(例如Logback的
logback.configurationFile
)。
26.4 Log Levels
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
. Example application.properties
:
Spring支持的所有日志系统都可以在Spring的Environment
中设置日志级别(例如在application.properties
设置),使用logging.level.*=LEVEL
进行设置,LEVEL
是TRACE,DEBUG,INFO,WARN,ERROR,FATAL,OFF中的一个。root
日志器可以用logging.level.root
来配置。例如在application.properties
中:
1 | logging.level.root=WARN |
By default Spring Boot remaps Thymeleaf
INFO
messages so that they are logged atDEBUG
level. This helps to reduce noise in the standard log output. SeeLevelRemappingAppender
for details of how you can apply remapping in your own configuration.
默认情况下Spring Boot重新映射Thymeleaf的
INFO
信息,为了它们能在DEBUG
级别进行输出。这能帮助减少标准日志输出中的噪声。关于怎样在你自己的配置中使用重新映射的更多细节请看LevelRemappingAppender
。
26.5 Custom log configuration
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
.
在类路径中通过包含恰当的库可以激活各种日志系统,在类路径的根目录中提供一个合适的配置文件可以对日志系统进行更进一步的定制,或者将配置文件放在Spring Environment
的logging.config
属性中指定的位置。
You can force Spring Boot to use a particular logging system using the org.springframework.boot.logging.LoggingSystem
system property. The value should be the fully-qualified class name of a LoggingSystem
implementation. You can also disable Spring Boot’s logging configuration entirely by using a value of none
.
你可以使用系统属性org.springframework.boot.logging.LoggingSystem
来强制Spring Boot使用一个特定的日志系统。它的值应该是全限定类名的LoggingSystem
实现。你也可以通过使用值none
来完全禁用Spring Boot的日志配置。
Since logging is initialized before the
ApplicationContext
is created, it isn’t possible to control logging from@PropertySources
in Spring@Configuration
files. System properties and the conventional Spring Boot external configuration files work just fine.
由于日志是在
ApplicationContext
创建之前初始化,因此不可能从Spring@Configuration
文件中的@PropertySources
来控制日志。系统属性和传统的Spring Boot外部配置文件可以工作的很好。
Depending on your logging system, the following files will be loaded:
根据你的日志系统,将会加载下面的文件:
Logging System | Customization |
---|---|
Logback | logback-spring.xml, logback-spring.groovy, logback.xml or logback.groovy |
Log4j2 | log4j2-spring.xml or log4j2.xml |
JDK (Java Util Logging) | logging.properties |
When possible we recommend that you use the
-spring
variants for your logging configuration (for examplelogback-spring.xml
rather thanlogback.xml
). If you use standard configuration locations, Spring cannot completely control log initialization.
我们建议你尽可能的使用
-spring
变种来进行日志配置(例如,logback-spring.xml
而不是logback.xml
)。如果你在使用标准的配置路径,Spring不能完全控制日志的初始化。
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.
在Java Java Util Logging中存在类加载问题,当从
executable jar
运行时会引起问题。我们建议你尽可能的避免它。
To help with the customization some other properties are transferred from the Spring Environment
to System properties:
为了帮助定制一些其它属性,从Spring Environment
中转移到系统属性中:
Spring Environment | System Property | Comments |
---|---|---|
logging.exception-conversion-word | LOG_EXCEPTION_CONVERSION_WORD | The conversion word that’s used when logging exceptions. |
logging.file | LOG_FILE | Used in default log configuration if defined. |
logging.path | LOG_PATH | Used in default log configuration if defined. |
logging.pattern.console | CONSOLE_LOG_PATTERN | The log pattern to use on the console (stdout). (Only supported with the default logback setup.) |
logging.pattern.file | FILE_LOG_PATTERN | The log pattern to use in a file (if LOG_FILE enabled). (Only supported with the default logback setup.) |
logging.pattern.level | LOG_LEVEL_PATTERN | The format to use to render the log level (default %5p). (Only supported with the default logback setup.) |
PID | PID | The current process ID (discovered if possible and when not already defined as an OS environment variable). |
Spring Environment | System Property | Comments |
---|---|---|
logging.exception-conversion-word | LOG_EXCEPTION_CONVERSION_WORD | 当日志出现异常时会用到这个转换词。 |
logging.file | LOG_FILE | 如果定义了,会在默认的日志配置中使用。 |
logging.path | LOG_PATH | 如果定义了,会在默认的日志配置中使用。 |
logging.pattern.console | CONSOLE_LOG_PATTERN | 用在控制台中的日志模式(stdout)。(只支持默认的Logback设置。) |
logging.pattern.file | FILE_LOG_PATTERN | 用在文件中的日志模式 (如果启用LOG_FILE )。(只支持默认的Logback设置。) |
logging.pattern.level | LOG_LEVEL_PATTERN | 这种模式用来实施日志级别(默认%5p )。 (只支持默认的Logback设置。) |
PID | PID | 当前的进程ID |
All the logging systems supported can consult System properties when parsing their configuration files. See the default configurations in spring-boot.jar
for examples.
当转换配置文件时,所有的日志系统都支持查询系统属性。例如spring-boot.jar
的默认配置。
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
:
as the delimiter between a property name and its default value and not:-
.
如果你在日志属性中想使用占位符,你应该试用Spring Boot的语法而不是底层框架的语法。尤其是,如果你在使用Logback,你应该使用
:
作为属性名和默认值之间的分隔符,而不是:-
。
You can add MDC and other ad-hoc content to log lines by overriding only the
LOG_LEVEL_PATTERN
(orlogging.pattern.level
with Logback). For example, if you uselogging.pattern.level=user:%X{user} %5p
then the default log format will contain an MDC entry for “user” if it exists, e.g.
1
2 2015-09-30 12:30:04.031 user:juergen INFO 22174 --- [ nio-8080-exec-0] demo.Controller
Handling authenticated request
你可以通过重写
LOG_LEVEL_PATTERN
(或Logback中的logging.pattern.level
)来添加MDC和其它的专门内容来日志行中。例如,你可以使用logging.pattern.level=user:%X{user} %5p
,默认的日志形式将包含MDC输入,如果它存在的话,例如:
1
2 2015-09-30 12:30:04.031 user:juergen INFO 22174 --- [ nio-8080-exec-0] demo.Controller
Handling authenticated request
26.6 Logback extensions
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.
Spring Boot包含许多Logback的扩展,这有助于进行更高级的配置。你可以在你的logback-spring.xml
配置文件中使用这些扩展。
You cannot use extensions in the standard
logback.xml
configuration file since it’s loaded too early. You need to either uselogback-spring.xml
or define alogging.config
property.
你不能在标准的
logback.xml
配置文件中使用扩展,因为它加载的太早了。你需要使用logback-spring.xml
或定义logging.config
属性。
26.6.1 Profile-specific configuration
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>
标签允许你自由的包含或排除基于激活的Spring profiles的配置的一部分。在<configuration>
元素的任何地方都支持Profile部分。使用name
属性来指定哪一个profile接受配置。多个profiles可以用一个逗号分隔的列表来指定。
1 | <springProfile name="staging"> |
26.6.2 Environment properties
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 in local
scope. If you need a fallback value in case the property is not set in the Environment
, you can use the defaultValue
attribute.
<springProperty>
标签允许你在Logback使用从Spring Environment
获得的属性。如果你想在你的Logback配置中访问application.properties
文件中的属性,这是非常有用的。这个标签与Logback的标准<property>
标签的作用方式类似,但不是为你指定的source
属性(从Environment
中)指定一个直接的value
。如果你需要在某个地方而不是在local
作用域中存储属性,你可以使用scope
属性。如果你需要一个备用值以防属性没有在Environment
中设置,你可以使用defaultValue
属性。
1 | <springProperty scope="context" name="fluentHost" source="myapp.fluentd.host" |
The
RelaxedPropertyResolver
is used to accessEnvironment
properties. If specify thesource
in dashed notation (my-property-name
) all the relaxed variations will be tried (myPropertyName
,MY_PROPERTY_NAME
etc).
RelaxedPropertyResolver
是用来访问Environment
属性。如果在破折号符号中指定了source
,则会尝试所有的不严格的变种(myPropertyName
,MY_PROPERTY_NAME
等)。