简体   繁体   English

使用log4j JsonLayout记录JSON对象

[英]Log JSON object with log4j JsonLayout

Hey i have a project that uses log4j and slf4j for logging. 嘿,我有一个使用log4j和slf4j进行记录的项目。 I configure the layout of the log to be JsonLayout. 我将日志的布局配置为JsonLayout。 Is it possible to log a JSON object while keeping the json format. 是否可以在保持json格式的同时记录JSON对象。

For Example : 例如 :

    JsonObject object = new JsonObject();
    object.addProperty("ID", 3);
    LOGGER.info("{}", object);

will output : 将输出:

{
  "timeMillis" : 1496579005079,
  "thread" : "main",
  "level" : "INFO",
  "loggerName" : "Logger",
  **"message" : "{\"ID\":3}",**
  "endOfBatch" : false,
  "loggerFqcn" : "org.apache.logging.slf4j.Log4jLogger",
  "threadId" : 1,
  "threadPriority" : 5
}

While i need it to output this: 虽然我需要它来输出此:

{
  "timeMillis" : 1496579005079,
  "thread" : "main",
  "level" : "INFO",
  "loggerName" : "Logger",
  **"message" : {"ID":3},**
  "endOfBatch" : false,
  "loggerFqcn" : "org.apache.logging.slf4j.Log4jLogger",
  "threadId" : 1,
  "threadPriority" : 5
}

There is an objectMessageAsJsonObject that should do this for you. 有一个objectMessageAsJsonObject应该为您执行此操作。 In your log4j2.xml: 在您的log4j2.xml中:

 <RollingFile name="json-log" fileName="build/log"
      filePattern="/var/log/.%d{yyyy-MM-dd}.log">
      <JSONLayout objectMessageAsJsonObject="true"/>    
 </RollingFile>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM