Kafka 如何在生产者日志时添加MDC

djp7away  于 7个月前  发布在  Apache
关注(0)|答案(2)|浏览(88)

我尝试在MDC中设置一个值,以显示在每个日志行中,但是当Kafka producer中有log.info(“”)时,日志不会显示我之前为MDC添加的值。
我有一个拦截器来设置correlationId的“default-value”,并在请求后清除MDC。

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                         Object handler) {
    MDC.put("correlationId", "correlation-id-to-be-set");
    return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                       @Nullable ModelAndView modelAndView){
    MDC.clear();
}

字符串
当MDC进入控制器时,我设置了它的correlationId值。

@RequestMapping(value = "/notifications", method = RequestMethod.POST, produces = {"application/json"})
@ResponseStatus(HttpStatus.CREATED)
@RolesAllowed({"ROLE_CREATE_NOTIFICATION"})
@LogMethodExecutionTime
public @ResponseBody
OutboundNotificationEvent createNotification(@Valid @RequestBody OutboundNotificationEvent notificationRequest,
                                             HttpServletRequest request){

    log.info("Request Received. CorrelationId {} ",notificationRequest.getCorrelationId());
    if(notificationRequest.getCorrelationId()!=null)
        MDC.put("correlationId", notificationRequest.getCorrelationId());

    bpmProducer.sendMessage(ArgosUtils.mapNotificationPayloadToBpmEvent(notificationRequest, MSG_RECEIVED, EVENT_RECEIVED));


Only for kafka logs isn't including the MDC msg previously added
2022-06-08 10:15:31.616 INFO {correlationId=correlation-id-to-be-set} 19608 - [nio-8080-exec-2] .a.c. UnsubscribedNo tificationsController:请求已收到。CorrelationId hq 12345678888 2022-06-08 10:15:33.734 INFO {} 19608 - [rest-services-1] c. u. b. u. n. a. p. UnsubscribedAlertsProducer:留言成功发送2022-06-08 10:15:33.735 INFO {} 19608 - [rest-services-1] c. u. b. u.n. argos.producers.BpmProducer:Entering BPM sendMessage EventCode:bk_argos_sent 2022-06-08 10:15:33.747 INFO {} 19608 - [rest-services-1] c.u.b.u.n.argos.producers.BpmProducer:Event sent to bpm topic EventCode:bk_argos_sent 2022-06-08 10:15:33.752 INFO {correlationId=hq12345678888} 19608 - [nio-8080-exec-2]
因此,正如您在时间戳之后的日志中看到的那样,{}内的INFO {}应该是仅为nio-8080-exec-2线程显示的MDC值,从BpmProducer和UnsubscribedAlertsProducer触发的日志(这是Kafka产生事件的类)没有在日志中包含之前添加的MDC值。我的问题是我需要做什么来在每一个日志行中显示correlationId,如果有任何问题,请让我知道,提前感谢。

5jvtdoz2

5jvtdoz21#

我通过在生产者回调(线程)中恢复MDC上下文解决了这个问题-至少对于回调日志来说是这样:

final Map<String, String> copyOfContextMap = MDC.getCopyOfContextMap();
this.producer.send(producerRecord, (recordMetadata, e) -> {
    MDC.setContextMap(copyOfContextMap); // Restore MDC context for kafka producer thread
    
    // ...
    
    MDC.clear(); // Clear MDC context for kafka producer thread
});

字符串
根据您的具体实现,您可能还必须为其他派生线程执行此操作。
它可能仍然缺少KafkaProducer线程本身创建的日志的上下文。

esbemjvw

esbemjvw2#

你的项目中应该有一个logback配置文件(logback-spring.xml)。在这个文件中,我们可以配置包级日志。
示例:在下面的配置中,mdc密钥将为com.company软件包的DEBUG日志打印,并将为其他软件包的INFO日志打印mdc密钥。

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <appender class="ch.qos.logback.core.rolling.RollingFileAppender" name="RFA">
    <encoder class="net.logstash.logback.encoder.LogstashEncoder">
      <includeCallerData>true</includeCallerData>
      <includeMdcKeyName>url</includeMdcKeyName>
      <includeMdcKeyName>service</includeMdcKeyName>
      <includeMdcKeyName>userId</includeMdcKeyName>
    </encoder>
    <file>logs/service.log</file>
  </appender>

  <springProfile name="!production">
    <logger additivity="false" level="DEBUG" name="com.company"> //check this
      <appender-ref ref="RFA"/>
    </logger>
    <root level="INFO">
      <appender-ref ref="RFA"/>
    </root>
  </springProfile>

</configuration>

字符串

相关问题