54. 当前 Span
Brave 支持表示 in-flight 操作的“当前 span”概念。您可以使用Tracer.currentSpan()
将自定义标记添加到 span,并使用Tracer.nextSpan()
创建任何 in-flight 的子项。
在 Sleuth 中,您可以自动装配
Tracer
bean 以通过tracer.currentSpan()
方法检索当前的 span。要检索当前 context,只需调用tracer.currentSpan().context()
。要将当前跟踪 ID 作为 String 获取,您可以使用traceIdString()
方法,如下所示:tracer.currentSpan().context().traceIdString()
。
54.1 手动在范围内设置 span
在编写新的检测时,将您在范围内创建的 span 放置为当前的 span 非常重要。这样做不仅允许用户使用Tracer.currentSpan()
访问它,而且还允许自定义(如 SLF4J MDC)查看当前跟踪 ID。
Tracer.withSpanInScope(Span)
促进了这一点,并且最方便地使用 try-with-resources 习语。每当调用外部 code(例如继续执行拦截器或其他操作)时,将 span 放在范围内,如下面的示例所示:
@Autowired Tracer tracer;
try (SpanInScope ws = tracer.withSpanInScope(span)) {
return inboundRequest.invoke();
} finally { // note the scope is independent of the span
span.finish();
}
在边缘情况下,您可能需要暂时清除当前的 span(对于 example,启动不应与当前请求关联的任务)。要执行 tso,将 null 传递给withSpanInScope
,如下面的示例所示:
@Autowired Tracer tracer;
try (SpanInScope cleared = tracer.withSpanInScope(null)) {
startBackgroundThread();
}