<commit_before><commit_msg>General WSGI instrumentation for many frameworks.<commit_after>from __future__ import print_function
import opentracing as ot
from instana import tracer, options
import opentracing.ext.tags as ext
import logging


class iWSGIMiddleware(object):
    """ Instana WSGI middleware """

    def __init__(self, app):
        self.app = app
        opts = options.Options(log_level=logging.DEBUG)
        ot.global_tracer = tracer.InstanaTracer(opts)
        self

    def __call__(self, environ, start_response):
        env = environ

        def new_start_response(status, headers, exc_info=None):
            """Modified start response with additional headers."""
            # ot.global_tracer.inject(span.context, ot.Format.HTTP_HEADERS, headers)
            res = start_response(status, headers, exc_info)
            span.set_tag(ext.HTTP_STATUS_CODE, status.split(' ')[0])
            span.finish()
            return res

        if 'HTTP_X_INSTANA_T' in env and 'HTTP_X_INSTANA_S' in env:
            ctx = ot.global_tracer.extract(ot.Format.HTTP_HEADERS, env)
            span = ot.global_tracer.start_span("wsgi", child_of=ctx)
        else:
            span = ot.global_tracer.start_span("wsgi")

        span.set_tag(ext.HTTP_URL, env['PATH_INFO'])
        span.set_tag("http.params", env['QUERY_STRING'])
        span.set_tag(ext.HTTP_METHOD, env['REQUEST_METHOD'])
        span.set_tag("http.host", env['HTTP_HOST'])

        return self.app(environ, new_start_response)


def make_middleware(app=None, *args, **kw):
    """ Given an app, return that app wrapped in iWSGIMiddleware """
    app = iWSGIMiddleware(app, *args, **kw)
    return app

{'fraction_non_alphanumeric': 0.10879904875148633, 'fraction_numerical': 0.0005945303210463733, 'mean_word_length': 3.0948905109489053, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7008749', 'n_tokens_mistral': 527, 'n_tokens_neox': 516, 'n_words': 115}