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:

日志级别与颜色的映射如下:

LevelColor
FATALRed
ERRORRed
WARNYellow
INFOGreen
DEBUGGreen
TRACEGreen

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.filelogging.pathExampleDescription
(none(none)Console only logging.
Specific file(none)my.logWrites to the specified log file. Names can be an exact location or relative to the current directory.
(none)Specific directory/var/logWrites spring.log to the specified directory. Names can be an exact location or relative to the current directory.

表 26.1. Logging属性

logging.filelogging.pathExampleDescription
(none(none)只输出到控制台
指定文件(none)my.log写入指定的日志文件。名字可以是一个绝对位置或相对于当前目录。
(none)Specific directory/var/logspring.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 SystemCustomization
Logbacklogback-spring.xml, logback-spring.groovy, logback.xml or logback.groovy
Log4j2log4j2-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 EnvironmentSystem PropertyComments
logging.exception-conversion-wordLOG_EXCEPTION_CONVERSION_WORDThe conversion word that’s used when logging exceptions.
logging.fileLOG_FILEUsed in default log configuration if defined.
logging.pathLOG_PATHUsed in default log configuration if defined.
logging.pattern.consoleCONSOLE_LOG_PATTERNThe log pattern to use on the console (stdout). (Only supported with the default logback setup.)
logging.pattern.fileFILE_LOG_PATTERNThe log pattern to use in a file (if LOG_FILE enabled). (Only supported with the default logback setup.)
logging.pattern.levelLOG_LEVEL_PATTERNThe format to use to render the log level (default %5p). (Only supported with the default logback setup.)
PIDPIDThe current process ID (discovered if possible and when not already defined as an OS environment variable).
Spring EnvironmentSystem PropertyComments
logging.exception-conversion-wordLOG_EXCEPTION_CONVERSION_WORD当日志出现异常时会用到这个转换词。
logging.fileLOG_FILE如果定义了,会在默认的日志配置中使用。
logging.pathLOG_PATH如果定义了,会在默认的日志配置中使用。
logging.pattern.consoleCONSOLE_LOG_PATTERN用在控制台中的日志模式(stdout)。(只支持默认的Logback设置。)
logging.pattern.fileFILE_LOG_PATTERN用在文件中的日志模式 (如果启用LOG_FILE)。(只支持默认的Logback设置。)
logging.pattern.levelLOG_LEVEL_PATTERN这种模式用来实施日志级别(默认%5p)。 (只支持默认的Logback设置。)
PIDPID当前的进程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等)。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值