22from tornado .stack_context import StackContextInconsistentError , _state
33
44from ...context import Context
5+ from ...provider import DefaultContextProvider
56
67
7- class TracerStackContext (object ):
8+ class TracerStackContext (DefaultContextProvider ):
89 """
910 A context manager that manages ``Context`` instances in a thread-local state.
1011 It must be used everytime a Tornado's handler or coroutine is used within a
@@ -19,8 +20,9 @@ class TracerStackContext(object):
1920 https://github.com/tornadoweb/tornado/issues/1063
2021 """
2122 def __init__ (self ):
22- self .active = True
23- self .context = Context ()
23+ super (TracerStackContext , self ).__init__ ()
24+ self ._active = True
25+ self ._context = Context ()
2426
2527 def enter (self ):
2628 """
@@ -53,10 +55,9 @@ def __exit__(self, type, value, traceback):
5355 self .new_contexts = None
5456
5557 def deactivate (self ):
56- self .active = False
58+ self ._active = False
5759
58- @classmethod
59- def active (cls ):
60+ def active (self ):
6061 """
6162 Return the ``Context`` from the current execution flow. This method can be
6263 used inside a Tornado coroutine to retrieve and use the current tracing context.
@@ -68,15 +69,14 @@ def active(cls):
6869 # if a Tornado loop is not available, it means that this method
6970 # has been called from a synchronous code, so we can rely in a
7071 # thread-local storage
71- return getattr ( _state , '__datadog_context' , None )
72+ return self . _local . get ( )
7273 else :
7374 # we're inside a Tornado loop so the TracerStackContext is used
74- for ctx in reversed (_state .contexts [0 ]):
75- if isinstance (ctx , cls ) and ctx . active :
76- return ctx . context
75+ for stack in reversed (_state .contexts [0 ]):
76+ if isinstance (stack , self . __class__ ) and stack . _active :
77+ return stack . _context
7778
78- @classmethod
79- def activate (cls , ctx ):
79+ def activate (self , ctx ):
8080 """
8181 Set the active ``Context`` for this async execution. If a ``TracerStackContext``
8282 is not found, the context is discarded.
@@ -87,12 +87,13 @@ def activate(cls, ctx):
8787 if io_loop is None :
8888 # because we're outside of an asynchronous execution, we store
8989 # the current context in a thread-local storage
90- setattr ( _state , '__datadog_context' , ctx )
90+ self . _local . set ( ctx )
9191 else :
9292 # we're inside a Tornado loop so the TracerStackContext is used
9393 for stack_ctx in reversed (_state .contexts [0 ]):
94- if isinstance (stack_ctx , cls ) and stack_ctx .active :
95- stack_ctx .context = ctx
94+ if isinstance (stack_ctx , self .__class__ ) and stack_ctx ._active :
95+ stack_ctx ._context = ctx
96+ return ctx
9697
9798
9899def run_with_trace_context (func , * args , ** kwargs ):
0 commit comments