如何使用 logstash-logback-encoder 自定义 JSON 日志记录的消息属性?

How to customize message attribute of JSON Logging using logstash-logback-encoder?

I am using logstash-logback-encoder to print logs in json format.

Below is my logback-spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="sample" class = "org.ssn.app.config.CustomLogService">
</appender>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder class="net.logstash.logback.encoder.LogstashEncoder">
    <provider class="net.logstash.logback.composite.loggingevent.ArgumentsJsonProvider"/>
    </encoder> 
    
 
  </appender>
  <logger name="org.ssn.app" additivity="false" level="DEBUG">
    <appender-ref ref="STDOUT"/>
</logger>
  <root level="INFO">
  
    <appender-ref ref="STDOUT"/>
    
  </root> 
  
  
</configuration>
  1. Below my code snippet
    JSONObject lJsonObj = new JSONObject();
    lJsonObj.put("dl_no","DL10252");
    logger.debug(lJsonObj.toString,Markers.append("ss","sss"));
  1. The output is below
{
    "@timestamp": "2021-06-17T18:49:07.914+05:30",
    "@version": "1",
    "message": "{\"dl_no\":\"DL10252\"}",
    "logger_name": "org.ssn.app.controller.TestController1",
    "thread_name": "http-nio-8080-exec-1",
    "level": "DEBUG",
    "level_value": 10000,
    "ss": "sss"
}

Is there is any way to modify the message attribute's value data type so that we can avoid "\" >back slashes? Because typically i want to put JSON or nested JSON inside message attribute's >value and want to view them without any backslashes

日志事件的 message 字段通常是字符串,因为大多数记录器语句都是字符串。

由于 message 字段是字符串,字符串值中的任何双引号字符 (") 都必须转义。这意味着如果 JSON 包含在消息字段值中,则双引号字符将被转义。

编码器无法知道消息值的格式是否正确 JSON。因此,它必须对其进行转义以确保为日志事件生成的 JSON 是正确的 JSON.

如果您有一个预序列化的 JSON 值要包含在 JSON 日志事件中,那么您可以使用 Markers.appendRawStructuredArguments.raw 添加您对不同字段(不是 message 字段)的值。

例如:

JSONObject lJsonObj = new JSONObject();
lJsonObj.put("dl_no", "DL10252");
String jsonString = lJsonObj.toString()

// using markers
logger.debug(Markers.appendRaw("my_field", jsonString), "my message");

// using structured arguments
logger.debug("my message", StructuredArguments.raw("my_field", jsonString));

这会产生类似的结果:

{
    "@timestamp": "2021-06-17T18:49:07.914+05:30",
    "@version": "1",
    "message": "my message",
    "logger_name": "org.ssn.app.controller.TestController1",
    "thread_name": "http-nio-8080-exec-1",
    "level": "DEBUG",
    "level_value": 10000,
    "my_field": {"dl_no" : "DL10252"}
}

或者,您可以让编码器序列化该值,而不是预先序列化 JSON 字符串。例如,以下将产生与上面相同的结果...

// using markers
logger.debug(Markers.append("my_field", Map.of("dl_no", "DL10252")), "my message");

// using structured arguments
logger.debug("my message", StructuredArguments.kv("my_field", Map.of("dl_no", "DL10252"));