Skip to content

Commit f58fd6f

Browse files
committed
Django 1.9 instrumentation
1 parent b121231 commit f58fd6f

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

instana/django19.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
from __future__ import print_function
2+
import opentracing as ot
3+
from instana import tracer, options
4+
import opentracing.ext.tags as ext
5+
6+
7+
DJ19_INSTANA_MIDDLEWARE = 'instana.django19.InstanaMiddleware19'
8+
9+
10+
class InstanaMiddleware19(object):
11+
""" Django 1.9 Middleware to provide request tracing for Instana """
12+
def __init__(self):
13+
opts = options.Options(service="Django")
14+
ot.global_tracer = tracer.InstanaTracer(opts)
15+
self.span = None
16+
self
17+
18+
def process_request(self, request):
19+
env = request.environ
20+
if 'HTTP_X_INSTANA_T' in env and 'HTTP_X_INSTANA_S' in env:
21+
ctx = ot.global_tracer.extract(ot.Format.HTTP_HEADERS, env)
22+
span = ot.global_tracer.start_span("django", child_of=ctx)
23+
else:
24+
span = ot.global_tracer.start_span("django")
25+
26+
span.set_tag(ext.HTTP_URL, env['PATH_INFO'])
27+
span.set_tag("http.params", env['QUERY_STRING'])
28+
span.set_tag(ext.HTTP_METHOD, request.method)
29+
span.set_tag("http.host", env['HTTP_HOST'])
30+
self.span = span
31+
32+
def process_response(self, request, response):
33+
self.span.set_tag(ext.HTTP_STATUS_CODE, response.status_code)
34+
ot.global_tracer.inject(self.span.context, ot.Format.HTTP_HEADERS, response)
35+
self.span.finish()
36+
return response
37+
38+
39+
40+
def hook(module):
41+
""" Hook method to install the Instana middleware into Django """
42+
if DJ19_INSTANA_MIDDLEWARE in module.settings.MIDDLEWARE_CLASSES:
43+
return
44+
45+
if type(module.settings.MIDDLEWARE_CLASSES) is tuple:
46+
module.settings.MIDDLEWARE_CLASSES = (DJ19_INSTANA_MIDDLEWARE,) + module.settings.MIDDLEWARE_CLASSES
47+
elif type(module.settings.MIDDLEWARE_CLASSES) is list:
48+
module.settings.MIDDLEWARE_CLASSES = [DJ19_INSTANA_MIDDLEWARE] + module.settings.MIDDLEWARE_CLASSES
49+
else:
50+
print("Instana: Couldn't add InstanaMiddleware to Django")

0 commit comments

Comments
 (0)