Logging

Spring Boot 没有强制的日志记录依赖项,除了由 Spring Framework 的 spring-jcl 模块通常提供的 Commons Logging API。要使用 Logback,你需要在类路径上包含 Logbackspring-jcl。执行此操作的推荐方法是通过 starter,其全部依赖于 spring-boot-starter-logging。对于 Web 应用程序,你只需要 spring-boot-starter-web,因为它会通过传递依赖项依赖于日志记录 starter。如果你使用 Maven,那么以下依赖项会为你添加日志记录:

Spring Boot has no mandatory logging dependency, except for the Commons Logging API, which is typically provided by Spring Framework’s spring-jcl module. To use Logback, you need to include it and spring-jcl on the classpath. The recommended way to do that is through the starters, which all depend on spring-boot-starter-logging. For a web application, you only need spring-boot-starter-web, since it depends transitively on the logging starter. If you use Maven, the following dependency adds logging for you:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

Spring Boot 有一个 LoggingSystem 抽象,它会尝试基于类路径的内容配置日志记录。如果 Logback 可用,则它会是首选。

Spring Boot has a LoggingSystem abstraction that attempts to configure logging based on the content of the classpath. If Logback is available, it is the first choice.

如果你需要对日志记录做出的唯一更改是设置各个记录器的级别,则可以在 application.properties 中使用“logging.level”前缀来实现,如下例所示:

If the only change you need to make to logging is to set the levels of various loggers, you can do so in application.properties by using the "logging.level" prefix, as shown in the following example:

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

你还可以使用 logging.file.name 设置将日志写入的文件的位置(除了控制台之外)。

You can also set the location of a file to which the log will be written (in addition to the console) by using logging.file.name.

要配置日志记录系统的更细粒度设置,你需要使用 LoggingSystem 支持的本机配置格式。默认情况下,Spring Boot 会从系统默认位置(例如 Logback 的 classpath:logback.xml)选取本机配置,但是你可以使用 configprop:logging.config[] 属性设置配置文件的位置。

To configure the more fine-grained settings of a logging system, you need to use the native configuration format supported by the LoggingSystem in question. By default, Spring Boot picks up the native configuration from its default location for the system (such as classpath:logback.xml for Logback), but you can set the location of the config file by using the configprop:logging.config[] property.

Configure Logback for Logging

如果你需要在 application.properties 能够实现的定制之外,对 Logback 应用定制,那么你需要添加一个标准的 Logback 配置文件。你可以将 logback.xml 文件添加到类路径根目录,以供 Logback 查找。如果你想使用 Spring Boot Logback extensions,也可以使用 logback-spring.xml

If you need to apply customizations to logback beyond those that can be achieved with application.properties, you will need to add a standard logback configuration file. You can add a logback.xml file to the root of your classpath for logback to find. You can also use logback-spring.xml if you want to use the Spring Boot Logback extensions.

Logback 文档详细介绍了 dedicated section that covers configuration

The Logback documentation has a dedicated section that covers configuration in some detail.

Spring Boot 提供了许多 Logback 配置,可在自己的配置中 included。这些 include 旨在允许重新应用某些常见 Spring Boot 惯例。

Spring Boot provides a number of logback configurations that can be included in your own configuration. These includes are designed to allow certain common Spring Boot conventions to be re-applied.

以下文件在 org/springframework/boot/logging/logback/ 下提供:

The following files are provided under org/springframework/boot/logging/logback/:

  • defaults.xml - Provides conversion rules, pattern properties and common logger configurations.

  • console-appender.xml - Adds a ConsoleAppender using the CONSOLE_LOG_PATTERN.

  • file-appender.xml - Adds a RollingFileAppender using the FILE_LOG_PATTERN and ROLLING_FILE_NAME_PATTERN with appropriate settings.

另外,对于早期版本的 Spring Boot,提供了传统 base.xml 文件以便兼容。

In addition, a legacy base.xml file is provided for compatibility with earlier versions of Spring Boot.

典型的自定义 logback.xml 文件可能如下:

A typical custom logback.xml file would look something like this:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
	<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
	<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
	<root level="INFO">
		<appender-ref ref="CONSOLE" />
	</root>
	<logger name="org.springframework.web" level="DEBUG"/>
</configuration>

您的 logback 配置文件还可以利用系统属性,LoggingSystem 会负责为您创建这些属性:

Your logback configuration file can also make use of System properties that the LoggingSystem takes care of creating for you:

  • ${PID}: The current process ID.

  • ${LOG_FILE}: Whether logging.file.name was set in Boot’s external configuration.

  • ${LOG_PATH}: Whether logging.file.path (representing a directory for log files to live in) was set in Boot’s external configuration.

  • ${LOG_EXCEPTION_CONVERSION_WORD}: Whether logging.exception-conversion-word was set in Boot’s external configuration.

  • ${ROLLING_FILE_NAME_PATTERN}: Whether logging.pattern.rolling-file-name was set in Boot’s external configuration.

Spring Boot 通过使用自定义 Logback 转换器还在控制台(但不在日志文件中)提供一些漂亮的 ANSI 彩色终端输出。请参阅 defaults.xml 配置中的 CONSOLE_LOG_PATTERN 以获取示例。

Spring Boot also provides some nice ANSI color terminal output on a console (but not in a log file) by using a custom Logback converter. See the CONSOLE_LOG_PATTERN in the defaults.xml configuration for an example.

如果类路径中存在 Groovy,则您也应该能够使用 logback.groovy 配置 Logback。如果存在,则此设置将被优先考虑。

If Groovy is on the classpath, you should be able to configure Logback with logback.groovy as well. If present, this setting is given preference.

Groovy 配置不支持 Spring 扩展。将不会检测到任何 logback-spring.groovy 文件。

Spring extensions are not supported with Groovy configuration. Any logback-spring.groovy files will not be detected.

Configure Logback for File-only Output

如果您想要禁用控制台记录,而只将输出写入文件,则您需要一个自定义 logback-spring.xml,该 logback-spring.xml 会导入 file-appender.xml 但不会导入 console-appender.xml,如下面的示例所示:

If you want to disable console logging and write output only to a file, you need a custom logback-spring.xml that imports file-appender.xml but not console-appender.xml, as shown in the following example:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
	<include resource="org/springframework/boot/logging/logback/defaults.xml" />
	<property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}spring.log}"/>
	<include resource="org/springframework/boot/logging/logback/file-appender.xml" />
	<root level="INFO">
		<appender-ref ref="FILE" />
	</root>
</configuration>

您还需要根据以下示例将 logging.file.name 添加到您的 application.propertiesapplication.yaml

You also need to add logging.file.name to your application.properties or application.yaml, as shown in the following example:

logging:
  file:
    name: "myapplication.log"

Configure Log4j for Logging

如果类路径中存在 Log4j 2,Spring Boot 会为记录配置支持该类。如果您使用 starter 组装依赖项,则必须排除 Logback,然后 include Log4j 2。如果您不使用 starter,则除了 Log4j 2,您还需要提供(至少)spring-jcl

Spring Boot supports Log4j 2 for logging configuration if it is on the classpath. If you use the starters for assembling dependencies, you have to exclude Logback and then include Log4j 2 instead. If you do not use the starters, you need to provide (at least) spring-jcl in addition to Log4j 2.

推荐的路径是通过 starter,尽管需要做一些调整。下面的示例展示了如何在 Maven 中设置 starter:

The recommended path is through the starters, even though it requires some jiggling. The following example shows how to set up the starters in Maven:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter</artifactId>
	<exclusions>
		<exclusion>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-logging</artifactId>
		</exclusion>
	</exclusions>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

Gradle 提供了几种不同的方法来设置启动器。一种方法是使用 module replacement。要实现此目的,请声明对 Log4j 2 启动器的依赖,并告诉 Gradle 默认日志记录启动器的任何出现都应由 Log4j 2 启动器替换,如下例所示:

Gradle provides a few different ways to set up the starters. One way is to use a {url-gradle-docs}/resolution_rules.html#sec:module_replacement[module replacement]. To do so, declare a dependency on the Log4j 2 starter and tell Gradle that any occurrences of the default logging starter should be replaced by the Log4j 2 starter, as shown in the following example:

dependencies {
	implementation "org.springframework.boot:spring-boot-starter-log4j2"
	modules {
		module("org.springframework.boot:spring-boot-starter-logging") {
			replacedBy("org.springframework.boot:spring-boot-starter-log4j2", "Use Log4j2 instead of Logback")
		}
	}
}

Log4j 启动器将常见日志记录要求的依赖项整合在一起(例如让 Tomcat 使用 java.util.logging,但使用 Log4j 2 配置输出)。

The Log4j starters gather together the dependencies for common logging requirements (such as having Tomcat use java.util.logging but configuring the output using Log4j 2).

要确保使用 java.util.logging 执行的调试日志记录路由到 Log4j 2,请通过将 java.util.logging.manager 系统属性设置为 org.apache.logging.log4j.jul.LogManager 来配置其 JDK logging adapter

To ensure that debug logging performed using java.util.logging is routed into Log4j 2, configure its JDK logging adapter by setting the java.util.logging.manager system property to org.apache.logging.log4j.jul.LogManager.

Use YAML or JSON to Configure Log4j 2

除了其默认的 XML 配置格式外,Log4j 2 还支持 YAML 和 JSON 配置文件。要配置 Log4j 2 以使用替代配置文件格式,请将适当的依赖项添加到类路径,并命名您的配置文件以匹配您选择的的文件格式,如下例所示:

In addition to its default XML configuration format, Log4j 2 also supports YAML and JSON configuration files. To configure Log4j 2 to use an alternative configuration file format, add the appropriate dependencies to the classpath and name your configuration files to match your chosen file format, as shown in the following example:

Format Dependencies File names

YAML

com.fasterxml.jackson.core:jackson-databind + com.fasterxml.jackson.dataformat:jackson-dataformat-yaml

log4j2.yaml + log4j2.yml

JSON

com.fasterxml.jackson.core:jackson-databind

log4j2.json + log4j2.jsn

Use Composite Configuration to Configure Log4j 2

Log4j 2 支持将多个配置文件组合成一个复合配置。要在 Spring Boot 中使用此支持,请使用一个或多个辅助配置文件的位置配置 configprop:logging.log4j2.config.override[]。辅助配置文件将与主配置合并,无论主配置的来源是 Spring Boot 的默认值、标准位置(如 log4j.xml)还是由 configprop:logging.config[] 属性配置的位置。

Log4j 2 has support for combining multiple configuration files into a single composite configuration. To use this support in Spring Boot, configure configprop:logging.log4j2.config.override[] with the locations of one or more secondary configuration files. The secondary configuration files will be merged with the primary configuration, whether the primary’s source is Spring Boot’s defaults, a standard location such as log4j.xml, or the location configured by the configprop:logging.config[] property.