log4j2 跳过记录附加信息

log4j2 skip logging additional information

log4j2 将原始消息包装在 "message" 属性中 我正在使用 JSON 布局

{
    "timeMillis": 1538154855953,
    "thread": "MyThred #19",
    "level": "INFO",
    "loggerName": "MyLogger",
    "message": "My log message",
    "endOfBatch": false,
    "loggerFqcn": "org.ops4j.pax.logging.slf4j.Slf4jLogger",
    "threadId": 63,
    "threadPriority": 5
}

我想避免额外的字段

只想收到如下消息

{
    "message": "My log message"
}

只想像打印语句一样打印数据 不需要额外的信息,如 loggerName、thread 等

我认为 "additional info" 是 JSON 布局的全部目的。如果您不想使用此布局提供的格式,那么我可以想到几个选项:

  1. 配置不同的布局,使其产生 JSON 输出。例如,您可以像这样使用 PatternLayout<PatternLayout pattern="{&quot;message&quot;:&quot;%m&quot;}%n" /> 产生这样的输出:{"message":"log message"}

这种方法的缺点是它只适用于非常简单的场景。如果你想记录一个比简单的字符串消息更复杂的数据结构,它不会很好地工作。

  1. 将您的消息序列化为 JSON 字符串,然后再将它们传递给您的记录器。这不需要任何特殊布局 - 您可以使用像 pattern="%m%n" 这样的简单模式,因为您的消息已经采用 JSON 格式。这将要求您每次将消息序列化,然后再将它们传递给记录器。

  2. 创建自定义 class 实现 log4j2 Message interface and is responsible for generating a JSON string based on the input you provide to its constructor. Then when you log you simply create an instance of your class and pass it the necessary input. With this approach you can incorporate the serialization into the message class itself rather than having to pre-serialize the data, and it's probably less work than creating a custom layout

我希望这能为您指明正确的方向。没有更详细的要求,很难提供准确的解决方案。