You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LoggingEventCompositeJsonEncoder中添加Spring属性或环境变量?

在Logback配置中添加来自application.properties的自定义字段

因为目标配置已经在application.properties中定义,Logback可以直接读取这些配置项,确实能简化操作,无需额外编写代码读取环境变量。

修改步骤及完整配置:

  1. 在<configuration>根节点下添加<property>标签,读取application.properties中的目标配置项
  2. 在<providers>内的<logLevel/>之后,添加<field>标签,将读取到的配置作为自定义字段加入日志输出

修改后的完整配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <!-- 读取application.properties中的配置项,这里假设你的配置键是app.env,可根据实际修改 -->
    <property name="APP_ENV" source="app.env"/>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
            <providers>
                <threadName />
                <logLevel />
                <!-- 添加自定义字段,key为你想要的日志字段名,value引用上面读取的配置 -->
                <field key="app_environment" value="${APP_ENV}"/>
                <loggerName>
                    <shortenedLoggerNameLength>36</shortenedLoggerNameLength>
                </loggerName>
                <arguments>
                    <includeNonStructuredArguments>false</includeNonStructuredArguments>
                </arguments>
                <stackTrace />
                <message />
            </providers>
        </encoder>
    </appender>

    <root level="DEBUG">
        <appender-ref ref="CONSOLE" />
    </root>
</configuration>

说明:

  • <property>标签的source属性对应application.properties中配置的键名(比如你实际配置的是service.env=test,就把source改成service.env)
  • <field>的key是日志JSON中显示的字段名称,可根据业务需求自定义
  • 如果你的配置项是通过系统环境变量注入到application.properties的,这个写法依然生效,因为Logback会优先读取系统环境变量,再读取配置文件中的值

内容的提问来源于stack exchange,提问作者Marcos Stefani Rosa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 22:37:57