此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Boot 3.4.3spring-doc.cadn.net.cn

Logging

Spring Boot 使用 Commons Logging 进行所有内部日志记录,但将底层日志实现保持开放状态。 为 Java Util LoggingLog4j2Logback 提供了默认配置。 在每种情况下,记录器都预先配置为使用控制台输出,并提供可选的文件输出。spring-doc.cadn.net.cn

默认情况下,如果使用Starters,则使用 Logback 进行日志记录。 还包括适当的 Logback 路由,以确保使用 Java Util Logging、Commons Logging、Log4J 或 SLF4J 的依赖库都能正常工作。spring-doc.cadn.net.cn

有很多可用于 Java 的日志记录框架。 如果上面的列表看起来令人困惑,请不要担心。 通常,您不需要更改日志记录依赖项,并且 Spring Boot 默认值可以正常工作。
将应用程序部署到 servlet 容器或应用程序服务器时,使用 Java Util Logging API 执行的日志记录不会路由到应用程序的日志中。 这可以防止容器或已部署到容器的其他应用程序执行的日志记录显示在应用程序的日志中。

日志格式

Spring Boot 的默认日志输出类似于以下示例:spring-doc.cadn.net.cn

2025-03-15T00:32:33.092Z  INFO 89777 --- [myapp] [           main] o.s.b.d.f.logexample.MyApplication       : Starting MyApplication using Java 17.0.14 with PID 89777 (/opt/apps/myapp.jar started by myuser in /opt/apps/)
2025-03-15T00:32:33.100Z  INFO 89777 --- [myapp] [           main] o.s.b.d.f.logexample.MyApplication       : No active profile set, falling back to 1 default profile: "default"
2025-03-15T00:32:35.981Z  INFO 89777 --- [myapp] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)
2025-03-15T00:32:36.036Z  INFO 89777 --- [myapp] [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2025-03-15T00:32:36.037Z  INFO 89777 --- [myapp] [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.39]
2025-03-15T00:32:36.270Z  INFO 89777 --- [myapp] [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2025-03-15T00:32:36.280Z  INFO 89777 --- [myapp] [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 3031 ms
2025-03-15T00:32:37.521Z  INFO 89777 --- [myapp] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path '/'
2025-03-15T00:32:37.547Z  INFO 89777 --- [myapp] [           main] o.s.b.d.f.logexample.MyApplication       : Started MyApplication in 6.14 seconds (process running for 7.054)
2025-03-15T00:32:37.569Z  INFO 89777 --- [myapp] [ionShutdownHook] o.s.b.w.e.tomcat.GracefulShutdown        : Commencing graceful shutdown. Waiting for active requests to complete
2025-03-15T00:32:37.594Z  INFO 89777 --- [myapp] [tomcat-shutdown] o.s.b.w.e.tomcat.GracefulShutdown        : Graceful shutdown complete

输出以下项目:spring-doc.cadn.net.cn

Logback 没有FATAL水平。 它被映射到ERROR.
如果你有spring.application.name属性,但不希望它被记录下来,你可以设置logging.include-application-namefalse.
如果你有spring.application.group属性,但不希望它被记录下来,你可以设置logging.include-application-groupfalse.
有关关联 ID 的更多详细信息,请参阅此文档

控制台输出

默认日志配置在写入消息时将消息回显到控制台。 默认情况下,ERROR-水平WARN-level 和INFO-级别的消息。 您还可以通过使用--debug旗。spring-doc.cadn.net.cn

$ java -jar myapp.jar --debug
您还可以指定debug=trueapplication.properties.

启用调试模式后,将配置一系列核心 Logger(嵌入式容器、Hibernate 和 Spring Boot)以输出更多信息。 启用调试模式不会将应用程序配置为使用DEBUG水平。spring-doc.cadn.net.cn

或者,您可以通过使用--traceflag(或trace=trueapplication.properties). 这样做可以为选定的核心 Logger(嵌入式容器、Hibernate 模式生成和整个 Spring 产品组合)启用跟踪日志记录。spring-doc.cadn.net.cn

颜色编码输出

如果您的终端支持 ANSI,则使用颜色输出来提高可读性。 您可以设置spring.output.ansi.enabled设置为支持的值以覆盖自动检测。spring-doc.cadn.net.cn

颜色编码是使用%clr转换词。 在最简单的形式中,转换器根据对数级别对输出进行着色,如以下示例所示:spring-doc.cadn.net.cn

%clr(%5p)

下表描述了对数级别到颜色的映射:spring-doc.cadn.net.cn

水平 颜色

FATALspring-doc.cadn.net.cn

spring-doc.cadn.net.cn

ERRORspring-doc.cadn.net.cn

spring-doc.cadn.net.cn

WARNspring-doc.cadn.net.cn

黄色spring-doc.cadn.net.cn

INFOspring-doc.cadn.net.cn

绿spring-doc.cadn.net.cn

DEBUGspring-doc.cadn.net.cn

绿spring-doc.cadn.net.cn

TRACEspring-doc.cadn.net.cn

绿spring-doc.cadn.net.cn

或者,您可以通过将颜色或样式作为转换选项来指定应使用的颜色或样式。 例如,要使文本变为黄色,请使用以下设置:spring-doc.cadn.net.cn

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

支持以下颜色和样式:spring-doc.cadn.net.cn

文件输出

默认情况下, Spring Boot 仅记录到控制台,不写入日志文件。 如果除了控制台输出之外还想写入日志文件,则需要设置logging.file.namelogging.file.path属性(例如,在application.properties). 如果同时设置了这两个属性,则logging.file.path被忽略,并且只有logging.file.name被使用。spring-doc.cadn.net.cn

下表显示了logging.*properties 可以一起使用:spring-doc.cadn.net.cn

表 1.日志记录属性
logging.file.name logging.file.path 描述

(无)spring-doc.cadn.net.cn

(无)spring-doc.cadn.net.cn

仅限控制台日志记录。spring-doc.cadn.net.cn

特定文件(例如my.log)spring-doc.cadn.net.cn

(无)spring-doc.cadn.net.cn

写入logging.file.name. 该位置可以是绝对位置,也可以是相对于当前目录的位置。spring-doc.cadn.net.cn

(无)spring-doc.cadn.net.cn

特定目录(例如/var/log)spring-doc.cadn.net.cn

spring.loglogging.file.path. 该目录可以是绝对目录,也可以是相对于当前目录的目录。spring-doc.cadn.net.cn

特定文件spring-doc.cadn.net.cn

特定目录spring-doc.cadn.net.cn

写入logging.file.name并忽略logging.file.path. 该位置可以是绝对位置,也可以是相对于当前目录的位置。spring-doc.cadn.net.cn

日志文件在达到 10 MB 时轮换,并且与控制台输出一样,ERROR-水平WARN-level 和INFO-level 消息。spring-doc.cadn.net.cn

日志记录属性独立于实际的日志记录基础结构。 因此,特定的配置键(例如logback.configurationFilefor Logback)不受 Spring Boot 管理。

文件旋转

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

支持以下轮换策略属性:spring-doc.cadn.net.cn

名字 描述

logging.logback.rollingpolicy.file-name-patternspring-doc.cadn.net.cn

用于创建日志存档的文件名模式。spring-doc.cadn.net.cn

logging.logback.rollingpolicy.clean-history-on-startspring-doc.cadn.net.cn

是否应在应用程序启动时进行日志存档清理。spring-doc.cadn.net.cn

logging.logback.rollingpolicy.max-file-sizespring-doc.cadn.net.cn

日志文件存档前的最大大小。spring-doc.cadn.net.cn

logging.logback.rollingpolicy.total-size-capspring-doc.cadn.net.cn

日志存档在被删除之前可以占用的最大大小。spring-doc.cadn.net.cn

logging.logback.rollingpolicy.max-historyspring-doc.cadn.net.cn

要保留的存档日志文件的最大数量(默认为 7)。spring-doc.cadn.net.cn

日志级别

所有受支持的日志记录系统都可以在 Spring 中设置 Logger 级别Environment(例如,在application.properties) 使用logging.level.<logger-name>=<level>哪里level是 TRACE、DEBUG、INFO、WARN、ERROR、FATAL 或 OFF 之一。 这root可以使用logging.level.root.spring-doc.cadn.net.cn

以下示例显示了application.properties:spring-doc.cadn.net.cn

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

还可以使用环境变量设置日志记录级别。 例如LOGGING_LEVEL_ORG_SPRINGFRAMEWORK_WEB=DEBUG将设置org.springframework.webDEBUG.spring-doc.cadn.net.cn

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

日志组

能够将相关的 logger 分组在一起,以便可以同时配置它们通常很有用。 例如,您可能通常会更改所有与 Tomcat 相关的 Logger 的日志记录级别,但您无法轻松记住顶级包。spring-doc.cadn.net.cn

为了帮助解决这个问题,Spring Boot 允许您在 Spring 中定义日志记录组Environment. 例如,以下是如何通过将 “tomcat” 组添加到application.properties:spring-doc.cadn.net.cn

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

定义后,您可以使用一行更改组中所有 logger 的级别:spring-doc.cadn.net.cn

logging.level.tomcat=trace
logging:
  level:
    tomcat: "trace"

Spring Boot 包括以下预定义的日志记录组,这些组可以开箱即用:spring-doc.cadn.net.cn

名字 Logging

Webspring-doc.cadn.net.cn

org.springframework.core.codec,org.springframework.http,org.springframework.web,org.springframework.boot.actuate.endpoint.web,org.springframework.boot.web.servlet.ServletContextInitializerBeansspring-doc.cadn.net.cn

SQLspring-doc.cadn.net.cn

org.springframework.jdbc.core,org.hibernate.SQL,LoggerListenerspring-doc.cadn.net.cn

使用日志关闭钩子

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

logging.register-shutdown-hook=false
logging:
  register-shutdown-hook: false

自定义日志配置

可以通过在 Classpath 中包含适当的库来激活各种日志记录系统,并且可以通过在 Classpath 的根目录中或以下 Spring 指定的位置提供合适的配置文件来进一步定制Environment财产:logging.config.spring-doc.cadn.net.cn

您可以通过使用org.springframework.boot.logging.LoggingSystemsystem 属性。 该值应为LoggingSystem实现。 你还可以通过使用none.spring-doc.cadn.net.cn

由于日志记录是在ApplicationContext时,无法从@PropertySources春季@Configuration文件。 更改日志记录系统或完全禁用它的唯一方法是通过 System properties。

根据您的日志记录系统,将加载以下文件:spring-doc.cadn.net.cn

测井系统 定制

Logback (日志返回)spring-doc.cadn.net.cn

logback-spring.xml,logback-spring.groovy,logback.xmllogback.groovyspring-doc.cadn.net.cn

日志 4j2spring-doc.cadn.net.cn

log4j2-spring.xmllog4j2.xmlspring-doc.cadn.net.cn

JDK(Java Util 日志记录)spring-doc.cadn.net.cn

logging.propertiesspring-doc.cadn.net.cn

如果可能,我们建议您使用-spring变体(例如logback-spring.xml而不是logback.xml). 如果使用标准配置位置, Spring 则无法完全控制日志初始化。
Java Util Logging 存在已知的类加载问题,这些问题会导致在从“可执行 jar”运行时出现问题。 我们建议您尽可能避免从“可执行 jar”运行时使用它。

为了帮助进行自定义,从 Spring 传输了一些其他属性Environment更改为 System properties。 这允许记录系统配置来使用属性。例如,将logging.file.nameapplication.propertiesLOGGING_FILE_NAME作为环境变量将导致LOG_FILESystem 属性。 下表描述了传输的属性:spring-doc.cadn.net.cn

Spring 环境 系统属性 评论

logging.exception-conversion-wordspring-doc.cadn.net.cn

LOG_EXCEPTION_CONVERSION_WORDspring-doc.cadn.net.cn

记录异常时使用的转换字。spring-doc.cadn.net.cn

logging.file.namespring-doc.cadn.net.cn

LOG_FILEspring-doc.cadn.net.cn

如果已定义,则在默认日志配置中使用它。spring-doc.cadn.net.cn

logging.file.pathspring-doc.cadn.net.cn

LOG_PATHspring-doc.cadn.net.cn

如果已定义,则在默认日志配置中使用它。spring-doc.cadn.net.cn

logging.pattern.consolespring-doc.cadn.net.cn

CONSOLE_LOG_PATTERNspring-doc.cadn.net.cn

要在控制台上使用的日志模式 (stdout)。spring-doc.cadn.net.cn

logging.pattern.dateformatspring-doc.cadn.net.cn

LOG_DATEFORMAT_PATTERNspring-doc.cadn.net.cn

日志日期格式的 Appender 模式。spring-doc.cadn.net.cn

logging.charset.consolespring-doc.cadn.net.cn

CONSOLE_LOG_CHARSETspring-doc.cadn.net.cn

用于控制台日志记录的字符集。spring-doc.cadn.net.cn

logging.threshold.consolespring-doc.cadn.net.cn

CONSOLE_LOG_THRESHOLDspring-doc.cadn.net.cn

用于控制台日志记录的日志级别阈值。spring-doc.cadn.net.cn

logging.pattern.filespring-doc.cadn.net.cn

FILE_LOG_PATTERNspring-doc.cadn.net.cn

要在文件中使用的日志模式(如果LOG_FILE已启用)。spring-doc.cadn.net.cn

logging.charset.filespring-doc.cadn.net.cn

FILE_LOG_CHARSETspring-doc.cadn.net.cn

用于文件日志记录的字符集(如果LOG_FILE已启用)。spring-doc.cadn.net.cn

logging.threshold.filespring-doc.cadn.net.cn

FILE_LOG_THRESHOLDspring-doc.cadn.net.cn

用于文件日志记录的日志级别阈值。spring-doc.cadn.net.cn

logging.pattern.levelspring-doc.cadn.net.cn

LOG_LEVEL_PATTERNspring-doc.cadn.net.cn

渲染日志级别(默认%5p).spring-doc.cadn.net.cn

logging.structured.format.consolespring-doc.cadn.net.cn

CONSOLE_LOG_STRUCTURED_FORMATspring-doc.cadn.net.cn

用于控制台日志记录的结构化日志记录格式。spring-doc.cadn.net.cn

logging.structured.format.filespring-doc.cadn.net.cn

FILE_LOG_STRUCTURED_FORMATspring-doc.cadn.net.cn

用于文件日志记录的结构化日志记录格式。spring-doc.cadn.net.cn

PIDspring-doc.cadn.net.cn

PIDspring-doc.cadn.net.cn

当前进程 ID(如果可能且尚未定义为 OS 环境变量,则已发现)。spring-doc.cadn.net.cn

如果使用 Logback,则还会传输以下属性:spring-doc.cadn.net.cn

Spring 环境 系统属性 评论

logging.logback.rollingpolicy.file-name-patternspring-doc.cadn.net.cn

LOGBACK_ROLLINGPOLICY_FILE_NAME_PATTERNspring-doc.cadn.net.cn

滚动日志文件名的模式(默认${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz).spring-doc.cadn.net.cn

logging.logback.rollingpolicy.clean-history-on-startspring-doc.cadn.net.cn

LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_STARTspring-doc.cadn.net.cn

是否在启动时清理存档日志文件。spring-doc.cadn.net.cn

logging.logback.rollingpolicy.max-file-sizespring-doc.cadn.net.cn

LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZEspring-doc.cadn.net.cn

最大日志文件大小。spring-doc.cadn.net.cn

logging.logback.rollingpolicy.total-size-capspring-doc.cadn.net.cn

LOGBACK_ROLLINGPOLICY_TOTAL_SIZE_CAPspring-doc.cadn.net.cn

要保留的日志备份的总大小。spring-doc.cadn.net.cn

logging.logback.rollingpolicy.max-historyspring-doc.cadn.net.cn

LOGBACK_ROLLINGPOLICY_MAX_HISTORYspring-doc.cadn.net.cn

要保留的存档日志文件的最大数量。spring-doc.cadn.net.cn

所有受支持的日志记录系统都可以在解析其配置文件时查阅 System properties。 请参阅spring-boot.jar例如:spring-doc.cadn.net.cn

如果要在日志记录属性中使用占位符,则应使用 Spring Boot 的语法,而不是底层框架的语法。 值得注意的是,如果您使用 Logback,则应使用:作为属性名称与其默认值之间的分隔符,而不使用:-.spring-doc.cadn.net.cn

您可以通过仅覆盖LOG_LEVEL_PATTERN(或logging.pattern.level与 Logback 一起使用)。 例如,如果您使用logging.pattern.level=user:%X{user} %5p,则默认日志格式包含 “user” 的 MDC 条目(如果存在),如以下示例所示。spring-doc.cadn.net.cn

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

结构化日志记录

结构化日志记录是一种技术,其中日志输出以定义明确、通常是机器可读的格式写入。 Spring Boot 支持结构化日志记录,并支持以下开箱即用的 JSON 格式:spring-doc.cadn.net.cn

要启用结构化日志记录,请将属性logging.structured.format.console(用于控制台输出)或logging.structured.format.file(用于文件输出)设置为要使用的格式的 ID。spring-doc.cadn.net.cn

如果您使用的是自定义日志配置,请更新您的配置以遵循CONSOLE_LOG_STRUCTURED_FORMATFILE_LOG_STRUCTURED_FORMAT系统属性。 拿CONSOLE_LOG_STRUCTURED_FORMAT例如:spring-doc.cadn.net.cn

<!-- replace your encoder with StructuredLogEncoder -->
<encoder class="org.springframework.boot.logging.logback.StructuredLogEncoder">
	<format>${CONSOLE_LOG_STRUCTURED_FORMAT}</format>
	<charset>${CONSOLE_LOG_CHARSET}</charset>
</encoder>

您还可以参考 Spring Boot 中包含的默认配置:spring-doc.cadn.net.cn

<!-- replace your PatternLayout with StructuredLogLayout -->
<StructuredLogLayout format="${sys:CONSOLE_LOG_STRUCTURED_FORMAT}" charset="${sys:CONSOLE_LOG_CHARSET}"/>

您还可以参考 Spring Boot 中包含的默认配置:spring-doc.cadn.net.cn

Elastic 通用架构

Elastic Common Schema 是一种基于 JSON 的日志记录格式。spring-doc.cadn.net.cn

要启用 Elastic Common Schema 日志格式,请设置相应的formatproperty 设置为ecs:spring-doc.cadn.net.cn

logging.structured.format.console=ecs
logging.structured.format.file=ecs
logging:
  structured:
    format:
      console: ecs
      file: ecs

日志行如下所示:spring-doc.cadn.net.cn

{"@timestamp":"2024-01-01T10:15:00.067462556Z","log.level":"INFO","process.pid":39599,"process.thread.name":"main","service.name":"simple","log.logger":"org.example.Application","message":"No active profile set, falling back to 1 default profile: \"default\"","ecs.version":"8.11"}

此格式还会将 MDC 中包含的每个键值对添加到 JSON 对象中。 您还可以使用 SLF4J Fluent 日志记录 API 通过 addKeyValue 方法将键值对添加到记录的 JSON 对象中。spring-doc.cadn.net.cn

service值可以使用logging.structured.ecs.service性能:spring-doc.cadn.net.cn

logging.structured.ecs.service.name=MyService
logging.structured.ecs.service.version=1
logging.structured.ecs.service.environment=Production
logging.structured.ecs.service.node-name=Primary
logging:
  structured:
    ecs:
      service:
        name: MyService
        version: 1.0
        environment: Production
        node-name: Primary
logging.structured.ecs.service.name将默认为spring.application.name如果未指定。
logging.structured.ecs.service.version将默认为spring.application.version如果未指定。

Graylog 扩展日志格式 (GELF)

Graylog 扩展日志格式是 Graylog 日志分析平台的一种基于 JSON 的日志记录格式。spring-doc.cadn.net.cn

要启用 Graylog 扩展日志格式,请设置相应的formatproperty 设置为gelf:spring-doc.cadn.net.cn

logging.structured.format.console=gelf
logging.structured.format.file=gelf
logging:
  structured:
    format:
      console: gelf
      file: gelf

日志行如下所示:spring-doc.cadn.net.cn

{"version":"1.1","short_message":"No active profile set, falling back to 1 default profile: \"default\"","timestamp":1725958035.857,"level":6,"_level_name":"INFO","_process_pid":47649,"_process_thread_name":"main","_log_logger":"org.example.Application"}

此格式还会将 MDC 中包含的每个键值对添加到 JSON 对象中。 您还可以使用 SLF4J Fluent 日志记录 API 通过 addKeyValue 方法将键值对添加到记录的 JSON 对象中。spring-doc.cadn.net.cn

可以使用logging.structured.gelf性能:spring-doc.cadn.net.cn

logging.structured.gelf.host=MyService
logging.structured.gelf.service.version=1
logging:
  structured:
    gelf:
      host: MyService
      service:
        version: 1.0
logging.structured.gelf.host将默认为spring.application.name如果未指定。
logging.structured.gelf.service.version将默认为spring.application.version如果未指定。

Logstash JSON 格式

Logstash JSON 格式是一种基于 JSON 的日志记录格式。spring-doc.cadn.net.cn

要启用 Logstash JSON 日志格式,请设置相应的formatproperty 设置为logstash:spring-doc.cadn.net.cn

logging.structured.format.console=logstash
logging.structured.format.file=logstash
logging:
  structured:
    format:
      console: logstash
      file: logstash

日志行如下所示:spring-doc.cadn.net.cn

{"@timestamp":"2024-01-01T10:15:00.111037681+02:00","@version":"1","message":"No active profile set, falling back to 1 default profile: \"default\"","logger_name":"org.example.Application","thread_name":"main","level":"INFO","level_value":20000}

此格式还会将 MDC 中包含的每个键值对添加到 JSON 对象中。 您还可以使用 SLF4J Fluent 日志记录 API 通过 addKeyValue 方法将键值对添加到记录的 JSON 对象中。spring-doc.cadn.net.cn

如果您添加标记,这些标记将显示在tagsstring 数组。spring-doc.cadn.net.cn

自定义结构化日志记录 JSON

Spring Boot 尝试为结构化日志记录的 JSON 名称和值输出选择合理的默认值。 但是,有时您可能希望根据自己的需要对 JSON 进行一些小的调整。 例如,您可能希望更改某些名称以匹配日志摄取系统的预期。 您可能还希望筛选掉某些成员,因为您发现它们没有用处。spring-doc.cadn.net.cn

以下属性允许您更改结构化日志记录 JSON 的编写方式:spring-doc.cadn.net.cn

财产 描述

logging.structured.json.include & logging.structured.json.excludespring-doc.cadn.net.cn

从 JSON 中筛选特定路径spring-doc.cadn.net.cn

logging.structured.json.renamespring-doc.cadn.net.cn

重命名 JSON 中的特定成员spring-doc.cadn.net.cn

logging.structured.json.addspring-doc.cadn.net.cn

向 JSON 添加其他成员spring-doc.cadn.net.cn

例如,以下内容将排除log.level重命名process.idprocid并添加一个固定的corpname田:spring-doc.cadn.net.cn

logging.structured.json.exclude=log.level
logging.structured.json.rename.process.id=procid
logging.structured.json.add.corpname=mycorp
logging:
  structured:
    json:
      exclude: log.level
      rename:
        process.id: procid
      add:
        corpname: mycorp
对于更高级的自定义,您可以使用StructuredLoggingJsonMembersCustomizer接口。 您可以使用logging.structured.json.customizer财产。 您还可以通过在META-INF/spring.factories文件。

自定义结构化日志记录堆栈跟踪

每当记录消息时出现异常,JSON 输出中都会包含完整的堆栈跟踪。 您的日志摄取系统处理此信息量的成本可能很高,因此您可能需要调整堆栈跟踪的打印方式。spring-doc.cadn.net.cn

为此,您可以使用以下一个或多个属性:spring-doc.cadn.net.cn

财产 描述

logging.structured.json.stacktrace.rootspring-doc.cadn.net.cn

last最后打印根项(与 Java 相同),或者first以首先打印根项。spring-doc.cadn.net.cn

logging.structured.json.stacktrace.max-lengthspring-doc.cadn.net.cn

应打印的最大长度spring-doc.cadn.net.cn

logging.structured.json.stacktrace.max-throwable-depthspring-doc.cadn.net.cn

每个堆栈追踪要打印的最大帧数(包括公共帧和禁止显示的帧)spring-doc.cadn.net.cn

logging.structured.json.stacktrace.include-common-framesspring-doc.cadn.net.cn

是否应包含或删除公共框架spring-doc.cadn.net.cn

logging.structured.json.stacktrace.include-hashesspring-doc.cadn.net.cn

如果应包含堆栈跟踪的哈希值spring-doc.cadn.net.cn

例如,以下内容将使用根优先堆栈跟踪,限制其长度,并包含哈希。spring-doc.cadn.net.cn

logging.structured.json.stacktrace.root=first
logging.structured.json.stacktrace.max-length=1024
logging.structured.json.stacktrace.include-common-frames=true
logging.structured.json.stacktrace.include-hashes=true
logging:
  structured:
    json:
      stacktrace:
        root: first
        max-length: 1024
        include-common-frames: true
        include-hashes: true

如果您需要完全控制堆栈跟踪打印,您可以设置logging.structured.json.stacktrace.printer更改为StackTracePrinter实现。 您也可以将其设置为logging-system强制使用常规日志记录系统堆栈跟踪输出。spring-doc.cadn.net.cn

StackTracePrinterimplementation 还可以包括一个 constructor 参数,该参数接受StandardStackTracePrinter如果它希望将进一步的自定义应用于从 properties.spring-doc.cadn.net.cn

支持其他结构化日志记录格式

Spring Boot 中的结构化日志记录支持是可扩展的,允许您定义自己的自定义格式。 为此,请实现StructuredLogFormatter接口。泛型类型参数必须是ILoggingEvent使用 Logback 和LogEvent当使用 Log4j2 时(这意味着您的实现与特定的日志记录系统相关联)。 然后,使用 log 事件调用您的实现,并返回String要记录,如以下示例所示:spring-doc.cadn.net.cn

import ch.qos.logback.classic.spi.ILoggingEvent;

import org.springframework.boot.logging.structured.StructuredLogFormatter;

class MyCustomFormat implements StructuredLogFormatter<ILoggingEvent> {

	@Override
	public String format(ILoggingEvent event) {
		return "time=" + event.getInstant() + " level=" + event.getLevel() + " message=" + event.getMessage() + "\n";
	}

}
import ch.qos.logback.classic.spi.ILoggingEvent
import org.springframework.boot.logging.structured.StructuredLogFormatter

class MyCustomFormat : StructuredLogFormatter<ILoggingEvent> {

	override fun format(event: ILoggingEvent): String {
		return "time=${event.instant} level=${event.level} message=${event.message}\n"
	}

}

As you can see in the example, you can return any format, it doesn’t have to be JSON.spring-doc.cadn.net.cn

To enable your custom format, set the property logging.structured.format.console or logging.structured.format.file to the fully qualified class name of your implementation.spring-doc.cadn.net.cn

Your implementation can use some constructor parameters, which are injected automatically. Please see the JavaDoc of StructuredLogFormatter for more details.spring-doc.cadn.net.cn

Logback Extensions

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.spring-doc.cadn.net.cn

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 logging.config property.
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

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 Spring Framework reference guide for more details. The following listing shows three sample profiles:spring-doc.cadn.net.cn

<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

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:spring-doc.cadn.net.cn

<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 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 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.spring-doc.cadn.net.cn

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 logging.config property.
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

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 Spring Framework reference guide for more details. The following listing shows three sample profiles:spring-doc.cadn.net.cn

<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

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.spring-doc.cadn.net.cn

The following example shows how to set Log4j2 properties named applicationName and applicationGroup that read spring.application.name and spring.application.group from the Spring Environment:spring-doc.cadn.net.cn

<Properties>
	<Property name="applicationName">${spring:spring.application.name}</Property>
	<Property name="applicationGroup">${spring:spring.application.group}</Property>
</Properties>
The lookup key should be specified in kebab case (such as my.property-name).

Log4j2 System Properties

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.spring-doc.cadn.net.cn

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-doc.cadn.net.cn

The Spring Environment is only considered when system properties and OS environment variables do not contain the value being loaded.
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.