Spring Boot 2.0.0参考手册_中英文对照_Part IV_26

文章作者: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默认的日志输出看起来如下:

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 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.

默认的日志配置会将信息输出到控制台。默认情况下会输出ERRORWARNINFO级别的信息。你也可以通过--debug来启动你的应用,从而启用“debug”模式。

$ java -jar myapp.jar --debug

you can also specify debug=true in your application.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转换词来配置。最简单的形式是根据日志级别进行颜色输出,例如:

%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:

或者,你可以通过在转换器中提供选项来指定应该试用的颜色或风格。例如,为了使文本显示黄色:

%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.filelogging.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时日志文件将循环,至于控制台输出,默认情况下只输出ERRORWARNINFO级别的信息。

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中:

logging.level.root=WARN
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR

By default Spring Boot remaps Thymeleaf INFO messages so that they are logged at DEBUG level. This helps to reduce noise in the standard log output. See LevelRemappingAppender 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 Environmentlogging.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 example logback-spring.xml rather than logback.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 (or logging.pattern.level with Logback). For example, if you use logging.pattern.level=user:%X{user} %5p then the default log format will contain an MDC entry for "user" if it exists, e.g.

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输入,如果它存在的话,例如:

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 use logback-spring.xml or define a logging.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可以用一个逗号分隔的列表来指定。

<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>

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属性。

<springProperty scope="context" name="fluentHost" source="myapp.fluentd.host"
        defaultValue="localhost"/>
<appender name="FLUENT" class="ch.qos.logback.more.appenders.DataFluentAppender">
    <remoteHost>${fluentHost}</remoteHost>
    ...
</appender>

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

 

RelaxedPropertyResolver是用来访问Environment属性。如果在破折号符号中指定了source,则会尝试所有的不严格的变种(myPropertyNameMY_PROPERTY_NAME等)。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,362评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,330评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,247评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,560评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,580评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,569评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,929评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,587评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,840评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,596评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,678评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,366评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,945评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,929评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,165评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,271评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,403评论 2 342

推荐阅读更多精彩内容