|
1 | 1 | from sqlalchemy.event import listen, remove |
2 | 2 |
|
3 | 3 | g_tracer = None |
| 4 | +g_trace_all = True |
4 | 5 |
|
5 | | -def init_tracing(tracer): |
| 6 | +def init_tracing(tracer, trace_all=False): |
6 | 7 | ''' |
7 | 8 | Set our global tracer. |
8 | 9 | Tracer objects from our pyramid/flask/django libraries |
9 | 10 | can be passed as well. |
10 | 11 | ''' |
11 | | - global g_tracer |
| 12 | + global g_tracer, g_trace_all |
12 | 13 | if hasattr(tracer, '_tracer'): |
13 | 14 | g_tracer = tracer._tracer |
14 | 15 | else: |
15 | 16 | g_tracer = tracer |
16 | 17 |
|
| 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 | + |
17 | 39 | def set_parent_span(stmt_obj, parent_span): |
18 | 40 | ''' |
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. |
21 | 43 | ''' |
22 | 44 | stmt_obj._parent_span = parent_span |
| 45 | + stmt_obj._traced = True |
23 | 46 |
|
24 | 47 | def has_parent_span(stmt_obj): |
25 | 48 | ''' |
@@ -63,13 +86,16 @@ def _before_cursor_handler(conn, cursor, statement, parameters, context, execute |
63 | 86 | if context.compiled is None: # PRAGMA |
64 | 87 | return |
65 | 88 |
|
| 89 | + # Don't trace if trace_all is disabled and the statement wasn't marked |
66 | 90 | 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) |
68 | 95 | operation_name = _get_operation_name(stmt_obj) |
69 | 96 |
|
70 | 97 | # Start a new span for this query. |
71 | 98 | span = g_tracer.start_span(operation_name=operation_name, child_of=parent_span) |
72 | | - |
73 | 99 | span.set_tag('component', 'sqlalchemy') |
74 | 100 | span.set_tag('db.type', 'sql') |
75 | 101 | span.set_tag('db.statement', _normalize_stmt(statement)) |
|
0 commit comments