Skip to content

Commit f31f08d

Browse files
committed
Allow the user to disable tracing all the queries.
For this case, an explicit call to set_traced() on every statement will be required to have it traced.
1 parent a7251b7 commit f31f08d

1 file changed

Lines changed: 32 additions & 6 deletions

File tree

sqlalchemy_opentracing/__init__.py

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,48 @@
11
from sqlalchemy.event import listen, remove
22

33
g_tracer = None
4+
g_trace_all = True
45

5-
def init_tracing(tracer):
6+
def init_tracing(tracer, trace_all=False):
67
'''
78
Set our global tracer.
89
Tracer objects from our pyramid/flask/django libraries
910
can be passed as well.
1011
'''
11-
global g_tracer
12+
global g_tracer, g_trace_all
1213
if hasattr(tracer, '_tracer'):
1314
g_tracer = tracer._tracer
1415
else:
1516
g_tracer = tracer
1617

18+
g_trace_all = trace_all
19+
20+
def get_traced(stmt_obj):
21+
'''
22+
Gets a bool indicating whether or not this
23+
statement is marked for tracing.
24+
'''
25+
return getattr(stmt_obj, '_traced', False)
26+
27+
def set_traced(stmt_obj):
28+
'''
29+
Mark a statement to be traced.
30+
'''
31+
stmt_obj._traced = True
32+
33+
def get_parent_span(stmt_obj):
34+
'''
35+
Gets a parent span for this statement, if any.
36+
'''
37+
return getattr(stmt_obj, '_parent_span', None)
38+
1739
def set_parent_span(stmt_obj, parent_span):
1840
'''
19-
Start tracing a given statement under
20-
a specific span.
41+
Marks a statement as a child of a span.
42+
It gets marked to be traced if it wasn't before.
2143
'''
2244
stmt_obj._parent_span = parent_span
45+
stmt_obj._traced = True
2346

2447
def has_parent_span(stmt_obj):
2548
'''
@@ -63,13 +86,16 @@ def _before_cursor_handler(conn, cursor, statement, parameters, context, execute
6386
if context.compiled is None: # PRAGMA
6487
return
6588

89+
# Don't trace if trace_all is disabled and the statement wasn't marked
6690
stmt_obj = context.compiled.statement
67-
parent_span = getattr(stmt_obj, '_parent_span', None)
91+
if not (g_trace_all or get_traced(stmt_obj)):
92+
return
93+
94+
parent_span = get_parent_span(stmt_obj)
6895
operation_name = _get_operation_name(stmt_obj)
6996

7097
# Start a new span for this query.
7198
span = g_tracer.start_span(operation_name=operation_name, child_of=parent_span)
72-
7399
span.set_tag('component', 'sqlalchemy')
74100
span.set_tag('db.type', 'sql')
75101
span.set_tag('db.statement', _normalize_stmt(statement))

0 commit comments

Comments
 (0)