|
23 | 23 | from opencensus.trace import tracer as tracer_module |
24 | 24 | from opencensus.trace.samplers import probability |
25 | 25 |
|
| 26 | +from django.db import connection |
26 | 27 | try: |
27 | 28 | from django.utils.deprecation import MiddlewareMixin |
28 | 29 | except ImportError: # pragma: NO COVER |
@@ -210,9 +211,38 @@ def process_request(self, request): |
210 | 211 | SPAN_THREAD_LOCAL_KEY, |
211 | 212 | span) |
212 | 213 |
|
| 214 | + connection.execute_wrappers.append(self._trace_db_call) |
| 215 | + |
213 | 216 | except Exception: # pragma: NO COVER |
214 | 217 | log.error('Failed to trace request', exc_info=True) |
215 | 218 |
|
| 219 | + def _trace_db_call(self, execute, sql, params, many, context): |
| 220 | + _tracer = execution_context.get_opencensus_tracer() |
| 221 | + if _tracer is not None: |
| 222 | + if many: |
| 223 | + method_name = 'executemany' |
| 224 | + else: |
| 225 | + method_name = 'execute' |
| 226 | + db_type = context['connection'].vendor |
| 227 | + # Note that although get_opencensus_tracer() returns a NoopTracer |
| 228 | + # if no thread local has been set, set_opencensus_tracer() does NOT |
| 229 | + # protect against setting None to the thread local - be defensive |
| 230 | + # here |
| 231 | + _span = _tracer.start_span() |
| 232 | + _span.name = '{}.query'.format(db_type) |
| 233 | + _span.span_kind = span_module.SpanKind.CLIENT |
| 234 | + _tracer.add_attribute_to_current_span( |
| 235 | + '{}.query'.format(db_type), sql) |
| 236 | + _tracer.add_attribute_to_current_span( |
| 237 | + '{}.cursor.method.name'.format(db_type), method_name) |
| 238 | + |
| 239 | + result = execute(sql, params, many, context) |
| 240 | + |
| 241 | + if _tracer is not None: |
| 242 | + _tracer.end_span() |
| 243 | + |
| 244 | + return result |
| 245 | + |
216 | 246 | def process_view(self, request, view_func, *args, **kwargs): |
217 | 247 | """Process view is executed before the view function, here we get the |
218 | 248 | function name add set it as the span name. |
|
0 commit comments