Skip to content
This repository was archived by the owner on Sep 17, 2025. It is now read-only.

Commit f39c289

Browse files
committed
Use Django 2.0 DB instrumentation too
Closes #356
1 parent 781b3cb commit f39c289

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

opencensus/trace/ext/django/middleware.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
from opencensus.trace import tracer as tracer_module
2424
from opencensus.trace.samplers import probability
2525

26+
from django.db import connection
2627
try:
2728
from django.utils.deprecation import MiddlewareMixin
2829
except ImportError: # pragma: NO COVER
@@ -210,9 +211,38 @@ def process_request(self, request):
210211
SPAN_THREAD_LOCAL_KEY,
211212
span)
212213

214+
connection.execute_wrappers.append(self._trace_db_call)
215+
213216
except Exception: # pragma: NO COVER
214217
log.error('Failed to trace request', exc_info=True)
215218

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+
216246
def process_view(self, request, view_func, *args, **kwargs):
217247
"""Process view is executed before the view function, here we get the
218248
function name add set it as the span name.

0 commit comments

Comments
 (0)