7. 电流跨度
Brave 支持一个 ”current span
“概念,它表示正在进行的作。
您可以使用Tracer.currentSpan()
将自定义标记添加到 Span,并使用Tracer.nextSpan()
创建 any is in-flight 的子项。
在 Sleuth 中,你可以自动装配Tracer bean 通过tracer.currentSpan() 方法。要检索当前上下文,只需调用tracer.currentSpan().context() .以 String 形式获取当前跟踪 ID
您可以使用traceIdString() 方法如下:tracer.currentSpan().context().traceIdString() . |
7.1. 在范围内手动设置 span
编写新插桩时,请务必将您在 scope 中创建的 span 作为当前 span。
这样做不仅允许用户使用Tracer.currentSpan()
,但它也允许自定义(如 SLF4J MDC)来查看当前跟踪 ID。
Tracer.withSpanInScope(Span)
有助于实现这一点,并且使用 try-with-resources 惯用语是最方便的。
每当可能调用外部代码(例如继续侦听器或其他方式)时,请将 span 置于范围内,如以下示例所示:
@Autowired Tracer tracer;
try (SpanInScope ws = tracer.withSpanInScope(span)) {
return inboundRequest.invoke();
} finally { // note the scope is independent of the span
span.finish();
}
在极端情况下,您可能需要临时清除当前范围(例如,启动不应与当前请求关联的任务)。要执行 tso,请将 null 传递给withSpanInScope
,如以下示例所示:
@Autowired Tracer tracer;
try (SpanInScope cleared = tracer.withSpanInScope(null)) {
startBackgroundThread();
}