Logging

Spring Boot为所有内部日志记录使用 Commons Logging,但会保留底层日志实现的开放性。提供了{apiref-openjdk}/java.logging/java/util/logging/package-summary.html[Java Util Logging]、 Log4j2Logback的默认配置。在每种情况下,预先配置记录器以使用控制台输出,也可以选择使用文件输出。

Spring Boot uses Commons Logging for all internal logging but leaves the underlying log implementation open. Default configurations are provided for {apiref-openjdk}/java.logging/java/util/logging/package-summary.html[Java Util Logging], Log4j2, and Logback. In each case, loggers are pre-configured to use console output with optional file output also available.

默认情况下,如果你使用"`Starters`",则Logback用于日志记录。还包括了适当的Logback路由,以确保使用Java Util Logging、Commons Logging、Log4J或SLF4J的依赖库可以正常工作。

By default, if you use the “Starters”, Logback is used for logging. Appropriate Logback routing is also included to ensure that dependent libraries that use Java Util Logging, Commons Logging, Log4J, or SLF4J all work correctly.

Java 可用很多日志记录框架。如果上述清单看起来很混乱,别担心。通常,您无需更改您的日志记录依赖关系,而且 Spring Boot 默认设置即可正常工作。

There are a lot of logging frameworks available for Java. Do not worry if the above list seems confusing. Generally, you do not need to change your logging dependencies and the Spring Boot defaults work just fine.

当您将应用程序部署到 servlet 容器或应用程序服务器时,使用 Java Util Logging API 执行的日志记录不会路由到应用程序的日志中。这会阻止由容器或已部署到容器的其他应用程序执行的日志记录出现在应用程序的日志中。

When you deploy your application to a servlet container or application server, logging performed with the Java Util Logging API is not routed into your application’s logs. This prevents logging performed by the container or other applications that have been deployed to it from appearing in your application’s logs.

Log Format

Spring Boot 的默认日志输出类似于以下示例:

The default log output from Spring Boot resembles the following example:

Unresolved include directive in modules/reference/pages/features/logging.adoc - include::ROOT:partial$logging/logging-format.txt[]

将输出以下项目:

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.

  • Application name: Enclosed in square brackets (logged by default only if configprop:spring.application.name[] is set)

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

  • Correlation ID: If tracing is enabled (not shown in the sample above)

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

  • The log message.

Logback 没有\“7\”级别。它映射为\“8\”。

Logback does not have a FATAL level. It is mapped to ERROR.

如果您有一个 configprop:spring.application.name[] 属性但不想将其记录,您可以将 configprop:logging.include-application-name[] 设置为\“9\”。

If you have a configprop:spring.application.name[] property but don’t want it logged you can set configprop:logging.include-application-name[] to false.

Console Output

默认日志配置会将消息在写入时回显到控制台。默认情况下,记录 @“11”- 级别、@“12”- 级别和 @“13”- 级别消息。您还可以通过使用 @“14” 标志启动应用程序来启用 @“10” 模式。

The default log configuration echoes messages to the console as they are written. By default, ERROR-level, WARN-level, 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

您还可以在 @“16” 中指定 @“15”。

You can also specify debug=true in your application.properties.

当启用调试模式时,选择核心记录器(嵌入式容器、Hibernate 和 Spring Boot)配置为输出更多信息。启用调试模式不会配置您的应用程序,使其记录所有 @“17” 级别的消息。

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.

或者,您还可以通过使用 @“20” 标志(或在 @“22” 中使用 @“21”)启动应用程序来启用 @“19” 模式。这样做会为选择的核心记录器(嵌入式容器、Hibernate 模式生成和整个 Spring 产品组合)启用跟踪日志记录。

Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).

Color-coded Output

如果您的终端支持 ANSI,将使用彩色输出以帮助提高可读性。您可以将 @“23” 设置为 @“24”,以覆盖自动检测。

If your terminal supports ANSI, color output is used to aid readability. You can set spring.output.ansi.enabled to a supported value to override the auto-detection.

使用 @“25” 转换词来配置颜色编码。在最简单的形式中,转换器根据日志级别对输出着色,如下例所示:

Color coding is configured by using the %clr conversion word. In its simplest form, the converter colors the output according to the log level, as shown in the following example:

%clr(%5p)

以下表格介绍了日志级别到颜色的映射:

The following table describes the mapping of log levels to colors:

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, use the following setting:

%clr(%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX}){yellow}

支持以下颜色和样式:

The following colors and styles are supported:

  • blue

  • cyan

  • faint

  • green

  • magenta

  • red

  • yellow

File Output

默认情况下,Spring Boot 只记录到控制台而不写入日志文件。如果您想在控制台输出之外写入日志文件,则需要设置一个 configprop:logging.file.name[] 或 configprop:logging.file.path[] 属性(例如,在 application.properties 中)。

By default, Spring Boot logs only to the console and does not write log files. If you want to write log files in addition to the console output, you need to set a configprop:logging.file.name[] or configprop:logging.file.path[] property (for example, in your application.properties).

以下表格展示了 logging.* 属性如何一起使用:

The following table shows how the logging.* properties can be used together:

Table 1. Logging properties
configprop:logging.file.name[] configprop:logging.file.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.

日志文件在达到 10 MB 时轮转,并且与控制台输出一样,默认记录 ERROR 级、WARN 级和 INFO 级消息。

Log files rotate when they reach 10 MB and, as with console output, ERROR-level, WARN-level, and INFO-level messages are logged by default.

日志记录属性与实际的记录基础设施无关。因此,具体的配置密钥(例如 Logback 的 logback.configurationFile)不由 Spring Boot 管理。

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.

File Rotation

如果您使用的是 Logback,可以使用 application.propertiesapplication.yaml 文件微调日志轮转设置。对于所有其他日志记录系统,您需要自己直接配置轮转设置(例如,如果您使用 Log4j2,则可以添加 log4j2.xmllog4j2-spring.xml 文件)。

If you are using the Logback, it is possible to fine-tune log rotation settings using your application.properties or application.yaml file. For all other logging system, you will need to configure rotation settings directly yourself (for example, if you use Log4j2 then you could add a log4j2.xml or log4j2-spring.xml file).

支持以下轮转策略属性:

The following rotation policy properties are supported:

Name Description

configprop:logging.logback.rollingpolicy.file-name-pattern[]

The filename pattern used to create log archives.

configprop:logging.logback.rollingpolicy.clean-history-on-start[]

If log archive cleanup should occur when the application starts.

configprop:logging.logback.rollingpolicy.max-file-size[]

The maximum size of log file before it is archived.

configprop:logging.logback.rollingpolicy.total-size-cap[]

The maximum amount of size log archives can take before being deleted.

configprop:logging.logback.rollingpolicy.max-history[]

The maximum number of archive log files to keep (defaults to 7).

Log Levels

所有支持的日志记录系统都能在 Spring Environment 中设置记录器级别(例如,在 application.properties 中),使用 logging.level.<logger-name>=<level>,其中 level 是 TRACE、DEBUG、INFO、WARN、ERROR、FATAL 或 OFF 之一。root 记录器可以使用 logging.level.root 进行配置。

All the supported logging systems can have the logger levels set in the Spring Environment (for example, in application.properties) by using logging.level.<logger-name>=<level> where level is one of TRACE, DEBUG, INFO, WARN, ERROR, FATAL, or OFF. The root logger can be configured by using logging.level.root.

以下示例展示了 application.properties 中的潜在日志记录设置:

The following example shows potential logging settings in application.properties:

logging:
  level:
    root: "warn"
    org.springframework.web: "debug"
    org.hibernate: "error"

也可以使用环境变量设置日志记录级别。例如,LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_WEB=DEBUGorg.springframework.web 设置为 DEBUG

It is also possible to set logging levels using environment variables. For example, LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_WEB=DEBUG will set org.springframework.web to DEBUG.

上述方法仅适用于包级别日志。由于松散绑定始终将环境变量转换为小写,因此无法配置此方法中单个类的日志记录。如果您需要配置类的日志记录,可以使用 the SPRING_APPLICATION_JSON 变量。

The above approach will only work for package level logging. Since relaxed binding always converts environment variables to lowercase, it is not possible to configure logging for an individual class in this way. If you need to configure logging for a class, you can use the SPRING_APPLICATION_JSON variable.

Log Groups

通常将相关的日志记录器组合在一起很有用,这样可以同时对其进行配置。例如,您可能经常更改 all Tomcat 相关日志记录器的日志级别,但您无法轻易记住顶级包。

It is often useful to be able to group related loggers together so that they can all be configured at the same time. For example, you might commonly change the logging levels for all Tomcat related loggers, but you can not easily remember top level packages.

为了帮助解决此问题,Spring Boot 允许您在 Spring Environment 中定义日志记录组。例如,以下是通过将其添加到 application.properties 中来定义 “tomcat” 组的方式:

To help with this, Spring Boot allows you to define logging groups in your Spring Environment. For example, here is how you could define a “tomcat” group by adding it to your application.properties:

logging:
  group:
    tomcat: "org.apache.catalina,org.apache.coyote,org.apache.tomcat"

定义后,您可以使用单行更改组中所有日志记录器的级别:

Once defined, you can change the level for all the loggers in the group with a single line:

logging:
  level:
    tomcat: "trace"

Spring Boot 包含以下预定义的日志组,可以开箱即用:

Spring Boot includes the following pre-defined logging groups that can be used out-of-the-box:

Name Loggers

web

org.springframework.core.codec, org.springframework.http, org.springframework.web, org.springframework.boot.actuate.endpoint.web, org.springframework.boot.web.servlet.ServletContextInitializerBeans

sql

org.springframework.jdbc.core, org.hibernate.SQL, org.jooq.tools.LoggerListener

Using a Log Shutdown Hook

为了在应用程序终止时释放日志记录资源,提供了一个关闭钩子,该钩子将在 JVM 退出后触发日志系统清理。除非您的应用程序作为 war 文件部署,否则此关闭钩子会自动注册。如果您的应用程序具有复杂的上下文层次结构,则关闭钩子可能无法满足您的需求。在发生这种情况时,请禁用关闭钩子并研究底层日志系统直接提供的选项。例如,Logback 提供 context selectors,允许在自己的上下文中创建每个 Logger。您可以使用 configprop:logging.register-shutdown-hook[] 属性来禁用关闭钩子。将它设置为 false 将禁用注册。您可以在 application.propertiesapplication.yaml 文件中设置属性:

In order to release logging resources when your application terminates, a shutdown hook that will trigger log system cleanup when the JVM exits is provided. This shutdown hook is registered automatically unless your application is deployed as a war file. If your application has complex context hierarchies the shutdown hook may not meet your needs. If it does not, disable the shutdown hook and investigate the options provided directly by the underlying logging system. For example, Logback offers context selectors which allow each Logger to be created in its own context. You can use the configprop:logging.register-shutdown-hook[] property to disable the shutdown hook. Setting it to false will disable the registration. You can set the property in your application.properties or application.yaml file:

logging:
  register-shutdown-hook: false

Custom Log Configuration

可以通过在类路径中包含适当的库来激活各种日志记录系统,并且可以通过在类路径的根目录或以下 Spring Environment 属性指定的位置提供合适的配置文件来进一步自定义:configprop:logging.config[]。

The various logging systems can be activated by including the appropriate libraries on the classpath and can be further customized by providing a suitable configuration file in the root of the classpath or in a location specified by the following Spring Environment property: configprop:logging.config[].

您可以通过使用 org.springframework.boot.logging.LoggingSystem 系统属性强制 Spring Boot 使用特定的日志记录系统。该值应该是 LoggingSystem 实现的完全限定的类名称。您还可以使用值 none 完全禁用 Spring Boot 的日志记录配置。

You can force Spring Boot to use a particular logging system by 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.

由于日志是在创建 ApplicationContext 时初始化的,因此无法在 Spring @Configuration 文件中从 @PropertySources 控制日志记录。更改日志记录系统或完全禁用它的唯一方法是通过系统属性。

Since logging is initialized before the ApplicationContext is created, it is not possible to control logging from @PropertySources in Spring @Configuration files. The only way to change the logging system or disable it entirely is through System properties.

根据您的日志记录系统,加载以下文件:

Depending on your logging system, the following files are 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

如果可能,我们建议您为您的日志记录配置使用 -spring 变体(例如,使用 logback-spring.xml 而不用 logback.xml)。如果您使用标准配置位置,Spring 无法完全控制日志初始化。

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.

Java Util Logging 存在已知的类加载问题,当从“可执行 jar”运行时会导致问题。如果您从“可执行 jar”运行,我们建议您在可以的情况下避免它。

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

为了帮助自定义,一些其他属性从 Spring Environment 传输到系统属性。这允许日志系统配置使用这些属性。例如,在 application.propertiesLOGGING_FILE_NAME 中将 logging.file.name 设置为环境变量将导致设置 LOG_FILE 系统属性。下表描述了传输的属性:

To help with the customization, some other properties are transferred from the Spring Environment to System properties. This allows the properties to be consumed by logging system configuration. For example, setting logging.file.name in application.properties or LOGGING_FILE_NAME as an environment variable will result in the LOG_FILE System property being set. The properties that are transferred are described in the following table:

Spring Environment System Property Comments

configprop:logging.exception-conversion-word[]

LOG_EXCEPTION_CONVERSION_WORD

The conversion word used when logging exceptions.

configprop:logging.file.name[]

LOG_FILE

If defined, it is used in the default log configuration.

configprop:logging.file.path[]

LOG_PATH

If defined, it is used in the default log configuration.

configprop:logging.pattern.console[]

CONSOLE_LOG_PATTERN

The log pattern to use on the console (stdout).

configprop:logging.pattern.dateformat[]

LOG_DATEFORMAT_PATTERN

Appender pattern for log date format.

configprop:logging.charset.console[]

CONSOLE_LOG_CHARSET

The charset to use for console logging.

configprop:logging.threshold.console[]

CONSOLE_LOG_THRESHOLD

The log level threshold to use for console logging.

configprop:logging.pattern.file[]

FILE_LOG_PATTERN

The log pattern to use in a file (if LOG_FILE is enabled).

configprop:logging.charset.file[]

FILE_LOG_CHARSET

The charset to use for file logging (if LOG_FILE is enabled).

configprop:logging.threshold.file[]

FILE_LOG_THRESHOLD

The log level threshold to use for file logging.

configprop:logging.pattern.level[]

LOG_LEVEL_PATTERN

The format to use when rendering the log level (default %5p).

PID

PID

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

如果你使用 Logback,还将转移以下属性:

If you use Logback, the following properties are also transferred:

Spring Environment System Property Comments

configprop:logging.logback.rollingpolicy.file-name-pattern[]

LOGBACK_ROLLINGPOLICY_FILE_NAME_PATTERN

Pattern for rolled-over log file names (default ${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz).

configprop:logging.logback.rollingpolicy.clean-history-on-start[]

LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_START

Whether to clean the archive log files on startup.

configprop:logging.logback.rollingpolicy.max-file-size[]

LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZE

Maximum log file size.

configprop:logging.logback.rollingpolicy.total-size-cap[]

LOGBACK_ROLLINGPOLICY_TOTAL_SIZE_CAP

Total size of log backups to be kept.

configprop:logging.logback.rollingpolicy.max-history[]

LOGBACK_ROLLINGPOLICY_MAX_HISTORY

Maximum number of archive log files to keep.

所有受支持的日志记录系统在解析它们的配置文件时都可以查阅系统属性。有关示例,请参见 spring-boot.jar 中的默认配置:

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

  • {code-spring-boot}/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/logback/defaults.xml[Logback]

  • {code-spring-boot}/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/log4j2/log4j2.xml[Log4j 2]

  • {code-spring-boot}/spring-boot-project/spring-boot/src/main/resources/org/springframework/boot/logging/java/logging-file.properties[Java Util logging]

如果你想在日志记录属性中使用占位符,你应仅使用 Spring Boot’s syntax 而不是底层框架的语法。尤其值得注意的是,如果你使用 Logback,你应使用 : 作为属性名称及其默认值之间的分隔符,而不能使用 :-

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 use Logback, you should use : as the delimiter between a property name and its default value and not use :-.

你可以通过仅覆盖 LOG_LEVEL_PATTERN (或使用 Logback 覆盖 logging.pattern.level)向日志行添加 MDC 和其他临时的内容。例如,如果你使用 logging.pattern.level=user:%X{user} %5p,则如果存在,默认日志格式将包含“user”的 MDC 条目,如下例所示。

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 contains an MDC entry for "user", if it exists, as shown in the following example.

2019-08-30 12:30:04.031 user:someone INFO 22174 --- [  nio-8080-exec-0] demo.Controller
Handling authenticated request

Logback Extensions

Spring Boot 包含了多个 Logback 扩展,可以帮助进行高级配置。你可以在 logback-spring.xml 配置文件中使用这些扩展。

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

因为标准 logback.xml 配置文件加载过早,所以你不能在其中使用扩展。你需要使用 logback-spring.xml 或定义一个 configprop:logging.config[] 属性。

Because the standard logback.xml configuration file is loaded too early, you cannot use extensions in it. You need to either use logback-spring.xml or define a configprop:logging.config[] property.

扩展不能与 Logback 的 configuration scanning 一起使用。如果你尝试这样做,对配置文件进行更改会导致记录了一个类似于以下某个错误:

The extensions cannot be used with Logback’s configuration scanning. If you attempt to do so, making changes to the configuration file results in an error similar to one of the following being logged:

ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProperty], current ElementPath is [[configuration][springProperty]]
ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:71 - no applicable action for [springProfile], current ElementPath is [[configuration][springProfile]]

Profile-specific Configuration

<springProfile> 标记允许您基于活动 Spring 配置文件任选包含或排除配置部分。可以在 <configuration> 元素中的任何位置支持配置文件部分。使用 name 属性指定接受配置的配置文件。<springProfile> 标记可以包含一个配置文件名(比如 staging)或一个配置文件表达式。一个配置文件表达式允许表达更复杂的配置文件逻辑,比如 production & (eu-central | eu-west))。查看 {url-spring-framework-docs}/core/beans/environment.html#beans-definition-profiles-java[Spring Framework 参考指南] 来获得更多详情。下列清单显示了三个示例配置文件:

The <springProfile> tag lets you 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. The <springProfile> tag can contain a profile name (for example staging) or a profile expression. A profile expression allows for more complicated profile logic to be expressed, for example production & (eu-central | eu-west). Check the {url-spring-framework-docs}/core/beans/environment.html#beans-definition-profiles-java[Spring Framework reference guide] for more details. The following listing shows three sample 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>

Environment Properties

<springProperty> 标记允许您公开 Spring Environment 的属性以供 Logback 使用。如果您希望在 Logback 配置中访问 application.properties 文件中的值,这样做非常有用。该标记的工作方式与 Logback 的标准 <property> 标记类似。不过,您不需要指定直接 value,而要指定该属性的 source(来自 Environment)。如果您需要在 local 作用域之外存储某个属性,可以使用 scope 属性。如果您需要一个回退值(以防属性未在 Environment 中设置),可以使用 defaultValue 属性。下列示例展示了如何公开属性以为 Logback 使用:

The <springProperty> tag lets you expose properties from the Spring Environment for use within Logback. Doing so 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. However, rather than specifying a direct value, you specify the source of the property (from the Environment). If you need to store the property somewhere other than in local scope, you can use the scope attribute. If you need a fallback value (in case the property is not set in the Environment), you can use the defaultValue attribute. The following example shows how to expose properties for use within Logback:

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

source 必须以短横线字符形式指定(比如 my.property-name)。不过,属性可以使用宽松规则添加到 Environment 中。

The source must be specified in kebab case (such as my.property-name). However, properties can be added to the Environment by using the relaxed rules.

Log4j2 Extensions

Spring Boot 包含了许多可以用来提供高级配置的 Log4j2 扩展。您可以在任何 log4j2-spring.xml 配置文件中使用这些扩展。

Spring Boot includes a number of extensions to Log4j2 that can help with advanced configuration. You can use these extensions in any log4j2-spring.xml configuration file.

因为标准的 log4j2.xml 配置文件过早加载,所以您不能在其中使用扩展。您需要使用 log4j2-spring.xml 或者定义一个 configprop:logging.config[] 属性。

Because the standard log4j2.xml configuration file is loaded too early, you cannot use extensions in it. You need to either use log4j2-spring.xml or define a configprop:logging.config[] property.

这些扩展取代了 Log4J 提供的 Spring Boot support 。您应该确保不将 org.apache.logging.log4j:log4j-spring-boot 模块包含在您的版本中。

The extensions supersede the Spring Boot support provided by Log4J. You should make sure not to include the org.apache.logging.log4j:log4j-spring-boot module in your build.

Profile-specific Configuration

<SpringProfile> 标记允许您基于活动 Spring 配置文件任选包含或排除配置部分。可以在 <Configuration> 元素中的任何位置支持配置文件部分。使用 name 属性指定接受配置的配置文件。<SpringProfile> 标记可以包含一个配置文件名(比如 staging)或一个配置文件表达式。一个配置文件表达式允许表达更复杂的配置文件逻辑,比如 production & (eu-central | eu-west))。查看 {url-spring-framework-docs}/core/beans/environment.html#beans-definition-profiles-java[Spring Framework 参考指南] 来获得更多详情。下列清单显示了三个示例配置文件:

The <SpringProfile> tag lets you 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. The <SpringProfile> tag can contain a profile name (for example staging) or a profile expression. A profile expression allows for more complicated profile logic to be expressed, for example production & (eu-central | eu-west). Check the {url-spring-framework-docs}/core/beans/environment.html#beans-definition-profiles-java[Spring Framework reference guide] for more details. The following listing shows three sample 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>

Environment Properties Lookup

如果您希望在 Log4j2 配置中引用 Spring Environment 中的属性,可以使用 spring: 前缀的 lookups 。如果您希望在 Log4j2 配置中访问 application.properties 文件中的值,这样做非常有用。

If you want to refer to properties from your Spring Environment within your Log4j2 configuration you can use spring: prefixed lookups. Doing so can be useful if you want to access values from your application.properties file in your Log4j2 configuration.

下列示例展示了如何设置一个名为 applicationName 的 Log4j2 属性,它从 Spring Environment 中读取 spring.application.name

The following example shows how to set a Log4j2 property named applicationName that reads spring.application.name from the Spring Environment:

<Properties>
	<Property name="applicationName">${spring:spring.application.name}</Property>
</Properties>

查找键应该以短横线字符形式指定(比如 my.property-name)。

The lookup key should be specified in kebab case (such as my.property-name).

Log4j2 System Properties

Log4j2 支持许多 System Properties ,它们可以用来配置各种项目。例如, log4j2.skipJansi 系统属性可以用来配置 ConsoleAppender 是否将尝试在 Windows 上使用 Jansi 输出流。

Log4j2 supports a number of System Properties that can be used to configure various items. For example, the log4j2.skipJansi system property can be used to configure if the ConsoleAppender will try to use a Jansi output stream on Windows.

可以在 Log4j2 初始化后加载的所有系统属性都可以从 Spring Environment 中获取。例如,您可以将 log4j2.skipJansi=false 添加到您的 application.properties 文件中,以让 ConsoleAppender 在 Windows 上使用 Jansi。

All system properties that are loaded after the Log4j2 initialization can be obtained from the Spring Environment. For example, you could add log4j2.skipJansi=false to your application.properties file to have the ConsoleAppender use Jansi on Windows.

Spring Environment 仅在系统属性和操作系统环境变量中不包含正在加载的值时才被考虑。

The Spring Environment is only considered when system properties and OS environment variables do not contain the value being loaded.

在 Log4j2 早期初始化期间加载的系统属性无法引用 Spring Environment 。例如,Log4j2 用于允许选择默认 Log4j2 实现的属性在 Spring Environment 可用之前使用。

System properties that are loaded during early Log4j2 initialization cannot reference the Spring Environment. For example, the property Log4j2 uses to allow the default Log4j2 implementation to be chosen is used before the Spring Environment is available.