需要在kafka生产者回调中从spring-sleuth添加跟踪ID
我将侦探启动器添加到我的POM中并创建一个kafka生产者。我正在寻找一种将当前trace_id添加到回调中的日志的方法。
ListenableFuture<SendResult<K, V>> send = kafkaTemplate.send(topic, data);
send.addCallback(
new ListenableFutureCallback<>() {
@Override
public void onFailure(Throwable throwable) {
log.error(
MessageFormat.format(
"Error when sending message {0} to Kafka", data.getGlobalUUID()),
throwable);
deferredResult.setErrorResult(
new MarkusKafkaInputException(
MessageFormat.format(
"Error proceed {0} with message: {1}",
data.getGlobalUUID(), throwable.getMessage())));
}
@Override
public void onSuccess(SendResult<K, V> result) {
log.trace(result.toString());
}
});
POM中的安全依赖-
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
我希望日志中有trace_id,这些记录用于回调中。还是没有办法异步获取trace_id?
答案 0 :(得分:1)
找到方法,但不确定它是否正确
private static class TracingCallback<K, V> implements ListenableFutureCallback<SendResult<K, V>> {
private final Span span;
private final Tracer tracer;
private TracingCallback(Span span, Tracer tracer) {
this.span = span;
this.tracer = tracer;
}
@Override
public void onFailure(Throwable throwable) {
try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) {
log.error("test111");
} finally {
span.finish();
}
}
@Override
public void onSuccess(SendResult<K, V> kvSendResult) {
try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) {
log.error("test111");
} finally {
span.finish();
}
}
}
并在代码中使用-
@Autowired private Tracer tracer;
...
ListenableFuture<SendResult<K, V>> send = kafkaTemplate.send(topic, data);
send.addCallback(new TracingCallback<>(tracer.currentSpan(), tracer));
...