Java log4j 支持 JSON 格式吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29387007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:54:43  来源:igfitidea点击:

Does log4j support JSON format?

javajsonlog4j

提问by Stefan

Is it possible to let log4j output its logging in JSON format by only altering the log4j.properties.xmlconfiguration file?
I make use of an old application that uses log4j 1.2. I only see the XML layout but no JSON layout.

是否可以仅通过更改log4j.properties.xml配置文件让 log4j 以 JSON 格式输出其日志记录?
我使用了一个使用log4j 1.2. 我只看到 XML 布局,但没有看到 JSON 布局。

采纳答案by chad chen

just use buildin PatternLayout is ok:

只需使用 buildin PatternLayout 就可以了:

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.encoding=UTF-8
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern={"debug_level":"%p","debug_timestamp":"%d{ISO8601}","debug_thread":"%t","debug_file":"%F", "debug_line":"%L","debug_message":"%m"}%n

will out put like:

会像这样:

{
    "debug_level" : "INFO",
    "debug_timestamp" : "2016-05-26 16:37:08,938",
    "debug_thread" : "main",
    "debug_file" : "TestLogOutPut.java",
    "debug_line" : "316",
    "debug_message" : "hello i am a log message"
}

回答by Anna Malai

Yes It is possible. Take a look at this linkIt can generate

对的,这是可能的。 看看这个链接可以生成

{
   "timestamp":1352412458890,
   "date":"Nov 8, 2012 10:07:38 PM",
   "hostname":"michael1",
   "username":"michael",
   "level":"INFO",
   "thread":"main",
   "classname":"uk.me.mjt.log4jjson.SimpleJsonLayoutTest",
   "filename":"SimpleJsonLayoutTest.java",
   "linenumber":25,
   "methodname":"testDemonstration",
   "message":"Example of some logging"
 }

回答by Karpov S.Y.

this is official JSON layout

这是官方的 JSON 布局

https://github.com/logstash/log4j-jsonevent-layout

https://github.com/logstash/log4j-jsonevent-layout

1) Add maven dependency https://mvnrepository.com/artifact/net.logstash.log4j/jsonevent-layout

1) 添加 maven 依赖https://mvnrepository.com/artifact/net.logstash.log4j/jsonevent-layout

<dependency>
    <groupId>net.logstash.log4j</groupId>
    <artifactId>jsonevent-layout</artifactId>
    <version>1.7</version>  
</dependency>

2) Add configuration to your log4j.propertiesfile

2)将配置添加到您的log4j.properties文件中

 log4j.rootCategory=WARN, RollingLog
 log4j.appender.RollingLog=org.apache.log4j.DailyRollingFileAppender
 log4j.appender.RollingLog.Threshold=TRACE
 log4j.appender.RollingLog.File=api.log
 log4j.appender.RollingLog.DatePattern=.yyyy-MM-dd
 log4j.appender.RollingLog.layout=net.logstash.log4j.JSONEventLayoutV1