@@ -57,24 +57,41 @@ def __exit__(self, type, value, traceback):
5757 def deactivate (self ):
5858 self ._active = False
5959
60+ def _has_io_loop (self ):
61+ """Helper to determine if we are currently in an IO loop"""
62+ return getattr (IOLoop ._current , 'instance' , None ) is not None
63+
64+ def _has_active_context (self ):
65+ """Helper to determine if we have an active context or not"""
66+ if not self ._has_io_loop ():
67+ return self ._local ._has_active_context ()
68+ else :
69+ # we're inside a Tornado loop so the TracerStackContext is used
70+ return self ._get_state_active_context () is not None
71+
72+ def _get_state_active_context (self ):
73+ """Helper to get the currently active context from the TracerStackContext"""
74+ # we're inside a Tornado loop so the TracerStackContext is used
75+ for stack in reversed (_state .contexts [0 ]):
76+ if isinstance (stack , self .__class__ ) and stack ._active :
77+ return stack ._context
78+ return None
79+
6080 def active (self ):
6181 """
6282 Return the ``Context`` from the current execution flow. This method can be
6383 used inside a Tornado coroutine to retrieve and use the current tracing context.
6484 If used in a separated Thread, the `_state` thread-local storage is used to
6585 propagate the current Active context from the `MainThread`.
6686 """
67- io_loop = getattr (IOLoop ._current , 'instance' , None )
68- if io_loop is None :
87+ if not self ._has_io_loop ():
6988 # if a Tornado loop is not available, it means that this method
7089 # has been called from a synchronous code, so we can rely in a
7190 # thread-local storage
7291 return self ._local .get ()
7392 else :
7493 # we're inside a Tornado loop so the TracerStackContext is used
75- for stack in reversed (_state .contexts [0 ]):
76- if isinstance (stack , self .__class__ ) and stack ._active :
77- return stack ._context
94+ return self ._get_state_active_context ()
7895
7996 def activate (self , ctx ):
8097 """
@@ -83,8 +100,7 @@ def activate(self, ctx):
83100 If used in a separated Thread, the `_state` thread-local storage is used to
84101 propagate the current Active context from the `MainThread`.
85102 """
86- io_loop = getattr (IOLoop ._current , 'instance' , None )
87- if io_loop is None :
103+ if not self ._has_io_loop ():
88104 # because we're outside of an asynchronous execution, we store
89105 # the current context in a thread-local storage
90106 self ._local .set (ctx )
0 commit comments