生成结构化日志Java
我是新来的Java。
我想问一下如何使用Java这样的bellow产生日志。
{"log_level":"INFO","timestamp":"2021-12-23T08:39:48.444706Z",
"event_type":"abc_c","capture_id":"400011","cap_pid":"00053716",
"deb":"0100","no_id":"0011",
"msg_id":"d8c5derbn5-63cb-11ec-8980-0242ac110004","module":"S_TH}
I'm new with JAVA.
I want to ask how can I generate logs like this bellow using java.
{"log_level":"INFO","timestamp":"2021-12-23T08:39:48.444706Z",
"event_type":"abc_c","capture_id":"400011","cap_pid":"00053716",
"deb":"0100","no_id":"0011",
"msg_id":"d8c5derbn5-63cb-11ec-8980-0242ac110004","module":"S_TH}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您想要日志文件中的JSON
(您的示例不是有效的JSON),
您可以使用 slf4j-json-logger
a href =“ https://www.baeldung.com/java-log-json-unput” rel =“ nofollow noreferrer”> baeldung文章讨论了更多的JSON记录解决方案。
Assuming that you want JSON in the log file
(your example is not valid JSON),
you can use slf4j-json-logger
Here is a Baeldung article that discusses more JSON logging solutions.
如果您使用的是slf4j和logback,则可以使用ch.qos.logback.contrib.json.jsonlaylayout,来自 https://github.com/qos-ch/logback-contrib/wiki/json 。
或者,如果您的目标是Grafana Loki,则可以直接通过 https:https:// loki4j。 github.io/loki-logback-appender/
对于log4j2,有内置的jsonlayout:
但是,这仅包括默认属性,例如时间戳,loglevel,logger名称和消息。如果要添加自定义属性,则SLF4J具有映射的诊断上下文:
LogBack将自动将所有MDC键值添加为“ MDC”属性下的JSON映射。
如果您使用的是log4j2,则MDC称为threadContext。
对于Log4J2,您需要将上下文键明确添加到JSONLAYOUT中。
If you're using SLF4j and logback, you can use the ch.qos.logback.contrib.json.JsonLayout from https://github.com/qos-ch/logback-contrib/wiki/JSON.
Or if your target is Grafana Loki, you can send the logs directly via https://loki4j.github.io/loki-logback-appender/
For log4j2, there's the built-in JsonLayout:
However, this will only include default attributes like timestamp, loglevel, logger name, and message. If you want to add custom attributes, SLF4J has an Mapped Diagnostic Context for that:
Logback will automatically add all MDC key-values as a JSON map under the "mdc" attribute.
If you're using log4j2, the MDC is called ThreadContext.
For log4j2, you need to explicitly add the context keys to the JsonLayout.