opencensus - 显式上下文管理
opencensus - explicit context management
我正在我的(异步)JVM 应用程序中实施 opencensus 跟踪。
但是我不明白上下文是如何传递的。
有时它似乎工作正常,有时来自不同请求的痕迹无缘无故地出现嵌套。
我的日志中也出现了此警告以及堆栈跟踪:
SEVERE: Context was not attached when detaching
如何显式创建根 span,以及如何将 parent/context 显式传递给子 span?
在 OpenCensus 中,我们有一个独立于 "Span" 或 "Tags" 的上下文概念。它表示随请求传播的 Map(它作为线程本地实现,因此在同步调用中会自动传播)。对于仅用于传播的 callbacks/async 调用(我们使用 io.grpc.Context 作为上下文的实现)使用此处定义的包装函数 https://github.com/grpc/grpc-java/blob/master/context/src/main/java/io/grpc/Context.java#L589。这将确保仅上下文传播,因此上下文映射中的条目将在不同线程之间传播。
如果您想在一个线程中启动 Span 并在另一个线程中结束它,请使用来自跟踪器 https://www.javadoc.io/doc/io.opencensus/opencensus-api/0.17.0 的 withSpan
方法:
class MyClass {
private static Tracer tracer = Tracing.getTracer();
void handleRequest(Executor executor) {
Span span = tracer.spanBuilder("MyRunnableSpan").startSpan();
// do some work before scheduling the async
executor.execute(Context.wrap(tracer.withSpan(span, new Runnable() {
@Override
public void run() {
try {
sendResult();
} finally {
span.end();
}
}
})));
}
}
这里有更多相关信息https://github.com/census-instrumentation/opencensus-specs/blob/master/trace/Span.md#span-creation
我正在我的(异步)JVM 应用程序中实施 opencensus 跟踪。
但是我不明白上下文是如何传递的。 有时它似乎工作正常,有时来自不同请求的痕迹无缘无故地出现嵌套。
我的日志中也出现了此警告以及堆栈跟踪:
SEVERE: Context was not attached when detaching
如何显式创建根 span,以及如何将 parent/context 显式传递给子 span?
在 OpenCensus 中,我们有一个独立于 "Span" 或 "Tags" 的上下文概念。它表示随请求传播的 Map(它作为线程本地实现,因此在同步调用中会自动传播)。对于仅用于传播的 callbacks/async 调用(我们使用 io.grpc.Context 作为上下文的实现)使用此处定义的包装函数 https://github.com/grpc/grpc-java/blob/master/context/src/main/java/io/grpc/Context.java#L589。这将确保仅上下文传播,因此上下文映射中的条目将在不同线程之间传播。
如果您想在一个线程中启动 Span 并在另一个线程中结束它,请使用来自跟踪器 https://www.javadoc.io/doc/io.opencensus/opencensus-api/0.17.0 的 withSpan
方法:
class MyClass {
private static Tracer tracer = Tracing.getTracer();
void handleRequest(Executor executor) {
Span span = tracer.spanBuilder("MyRunnableSpan").startSpan();
// do some work before scheduling the async
executor.execute(Context.wrap(tracer.withSpan(span, new Runnable() {
@Override
public void run() {
try {
sendResult();
} finally {
span.end();
}
}
})));
}
}
这里有更多相关信息https://github.com/census-instrumentation/opencensus-specs/blob/master/trace/Span.md#span-creation