|
| 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 | + if self.span: |
| 34 | + self.span.set_tag(ext.HTTP_STATUS_CODE, response.status_code) |
| 35 | + ot.global_tracer.inject(self.span.context, ot.Format.HTTP_HEADERS, response) |
| 36 | + self.span.finish() |
| 37 | + self.span = None |
| 38 | + return response |
| 39 | + |
| 40 | + |
| 41 | + |
| 42 | +def hook(module): |
| 43 | + """ Hook method to install the Instana middleware into Django """ |
| 44 | + if DJ19_INSTANA_MIDDLEWARE in module.settings.MIDDLEWARE_CLASSES: |
| 45 | + return |
| 46 | + |
| 47 | + if type(module.settings.MIDDLEWARE_CLASSES) is tuple: |
| 48 | + module.settings.MIDDLEWARE_CLASSES = (DJ19_INSTANA_MIDDLEWARE,) + module.settings.MIDDLEWARE_CLASSES |
| 49 | + elif type(module.settings.MIDDLEWARE_CLASSES) is list: |
| 50 | + module.settings.MIDDLEWARE_CLASSES = [DJ19_INSTANA_MIDDLEWARE] + module.settings.MIDDLEWARE_CLASSES |
| 51 | + else: |
| 52 | + print("Instana: Couldn't add InstanaMiddleware to Django") |
0 commit comments