2015-04-01 127 views
14

是否可以讓log4j通過只更改log4j.properties.xml配置文件以JSON格式輸出日誌?
我使用使用log4j 1.2的舊應用程序。我只看到XML佈局但沒有JSON佈局。log4j是否支持JSON格式?

回答

18

只是使用的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 

會出來放像:

{ 
    "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" 
} 
+0

真棒......工作就像一個魅力.. – 2017-02-03 08:30:47

+9

如果郵件中包含這將打破' 「'。 – 2017-02-28 10:09:29

+0

當錯誤消息包含「\ n」等時,這不能工作 – xuanyuanaosheng 2018-01-18 11:17:52

1

是的這是可能的。 Take a look at this link 它可以產生

{ 
    "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" 
} 
15

這是官方JSON佈局

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

1)添加行家依賴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)添加配置到您的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