opencensus-java icon indicating copy to clipboard operation
opencensus-java copied to clipboard

Add API to get the current `TagContext` or `Span` without loading the implementation

Open sebright2 opened this issue 7 years ago • 3 comments

Currently there are two ways to get the current TagContext or Span, but neither one supports the case where another application or library needs to get the current value during program initialization:

  • Tagger.getCurrentTagContext() or Tracer.getCurrentSpan(): These methods are part of the core API. However, they require the global Tagger or Tracer to be loaded, which could cause an error in initialization order if the method is called during initialization. See the discussion about this problem at https://github.com/census-instrumentation/opencensus-java/pull/1371#discussion_r211441000.

  • ContextUtils.TAG_CONTEXT_KEY.get() or ContextUtils.CONTEXT_SPAN_KEY.get(): These fields avoid the initialization order issue, but they are in "unsafe" packages because they rely on details of the gRPC context. Code outside of the repository should avoid using them.

opencensus-api could provide two additional methods that don't expose details of the gRPC context and don't force the implementation to be loaded. Here is an example for TagContext:

public static TagContext getCurrentTagContext() {
  return io.opencensus.tags.unsafe.ContextUtils.TAG_CONTEXT_KEY.get();
}

The documentation could still encourage use of the Tagger and Tracer methods in code that doesn't run during initialization.

sebright2 avatar Oct 25 '18 23:10 sebright2

you can use directly the unsafe API in this case instead of adding new public methods.

bogdandrutu avatar Nov 02 '18 17:11 bogdandrutu

In this case where an initialization ordering is a problem please use the unsafe package.

bogdandrutu avatar Nov 13 '18 19:11 bogdandrutu

We talked offline, and I'm reopening this issue because the proposed API handles the initialization ordering issue without exposing as much detail about the inplementation of the opencensus-java contexts. However, it should still be harder to find than Tagger.getCurrentTagContext()/Tracer.getCurrentSpan(), which should be used in most cases.

The reason that I opened this issue is that opencensus-contrib-log-correlation-stackdriver accesses the current span context, and it needs to handle logging that could happen early in initialization. It currently accesses ContextUtils.CONTEXT_SPAN_KEY directly: https://github.com/census-instrumentation/opencensus-java/blob/7a565481d75d1ecf45cb84651e277cc57ba54a47/contrib/log_correlation/stackdriver/src/main/java/io/opencensus/contrib/logcorrelation/stackdriver/OpenCensusTraceLoggingEnhancer.java#L101 It would be better if it could use an API with more encapsulation, especially if it were to be moved to a separate project.

sebright2 avatar Feb 06 '19 21:02 sebright2