gpt4 book ai didi

java - 如何使用 Logback 更改 JSON 输出中的键名?

转载 作者:行者123 更新时间:2023-12-05 00:57:45 27 4
gpt4 key购买 nike

这是我的 logback 配置。

<springProfile name="prod">
<root level="info">
<appender name="naki" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>${logging_level}</level> <!-- setup via ENV variable log level -->
</filter>
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="ch.qos.logback.contrib.json.classic.JsonLayout">
<timestampFormat>yyyy-MM-dd'T'HH:mm:ss.SSSX</timestampFormat>
<timestampFormatTimezoneId>Etc/UTC</timestampFormatTimezoneId>
<appendLineSeparator>true</appendLineSeparator> <!-- don't forget line break -->

<jsonFormatter class="ch.qos.logback.contrib.jackson.JacksonJsonFormatter">
<prettyPrint>false
</prettyPrint> <!-- in prod never pretty print, line breaks are considered as separate log entry -->
</jsonFormatter>
</layout>
</encoder>
</appender>
</root>
</springProfile>

<springProfile name="dev">
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<root level="info">
<appender-ref ref="CONSOLE"/>
</root>
</springProfile>

这是我得到的输出:

{"timestamp":"2020-01-13T13:38:38.001Z","level":"INFO","thread":"main","logger":"com.nakipower.identity.api.config.Application","message":"Started Application in 8.605 seconds (JVM running for 9.439)","context":"default"}

如何将 JSON level 键名重命名为 severity?所以,我得到 "severity":"INFO" 而不是 "level":"INFO"。在使用 logback 配置日志记录时,我实际上可以重命名 JSON 键名吗?

最佳答案

您可以扩展 ch.qos.logback.contrib.jackson.JacksonJsonFormatter 并覆盖 toJsonString(Map m) 方法。在那里,您可以将给定 map 中的 level 条目替换为具有键 severity 的新条目。

public class CustomJsonFormatter extends JacksonJsonFormatter{

@Override
public String toJsonString(Map map) throws IOException {
map.put("severity", map.get("level"));
map.remove("level");
return super.toJsonString(map);
}
}

在您的 xml 配置中,在 jsonFormatter 标记中指向您刚刚创建的新格式化程序

<appender name="naki" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level> <!-- setup via ENV variable log level -->
</filter>
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
<layout class="ch.qos.logback.contrib.json.classic.JsonLayout">
<timestampFormat>yyyy-MM-dd'T'HH:mm:ss.SSSX</timestampFormat>
<timestampFormatTimezoneId>Etc/UTC</timestampFormatTimezoneId>
<appendLineSeparator>true</appendLineSeparator> <!-- don't forget line break -->

<jsonFormatter class="mypackage.CustomJsonFormatter"> <!-- Here point to your custom json formatter -->
<prettyPrint>false
</prettyPrint> <!-- in prod never pretty print, line breaks are considered as separate log entry -->
</jsonFormatter>
</layout>
</encoder>
</appender>

关于java - 如何使用 Logback 更改 JSON 输出中的键名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59718108/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com