Python opentracing.ext.tags.HTTP_STATUS_CODE Examples

The following are 17 code examples of opentracing.ext.tags.HTTP_STATUS_CODE(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module opentracing.ext.tags , or try the search function .
Example #1
Source File: vanilla.py    From python-sensor with MIT License 6 votes vote down vote up
def after_request_with_instana(response):
    scope = None
    try:
        # If we're not tracing, just return
        if not hasattr(flask.g, 'scope'):
            return response

        scope = flask.g.scope
        if scope is not None:
            span = scope.span

            if 500 <= response.status_code <= 511:
                span.mark_as_errored()

            span.set_tag(ext.HTTP_STATUS_CODE, int(response.status_code))
            tracer.inject(scope.span.context, opentracing.Format.HTTP_HEADERS, response.headers)
            response.headers.add('Server-Timing', "intid;desc=%s" % scope.span.context.trace_id)
    except:
        logger.debug("Flask after_request", exc_info=True)
    finally:
        if scope is not None:
            scope.close()
            flask.g.scope = None
        return response 
Example #2
Source File: requests.py    From opentracing-python-instrumentation with MIT License 6 votes vote down vote up
def _get_send_wrapper(self):
        def send_wrapper(http_adapter, request, **kwargs):
            """Wraps HTTPAdapter.send"""
            request_wrapper = self.RequestWrapper(request=request)
            span = before_http_request(request=request_wrapper,
                                       current_span_extractor=current_span_func
                                       )
            with span:
                response = _HTTPAdapter_send(http_adapter, request, **kwargs)
                if getattr(response, 'status_code', None) is not None:
                    span.set_tag(tags.HTTP_STATUS_CODE, response.status_code)
                if self.response_handler_hook is not None:
                    self.response_handler_hook(response, span)
            return response

        return send_wrapper 
Example #3
Source File: with_blinker.py    From python-sensor with MIT License 6 votes vote down vote up
def request_finished_with_instana(sender, response, **extra):
    scope = None
    try:
        if not hasattr(flask.g, 'scope'):
            return

        scope = flask.g.scope
        if scope is not None:
            span = scope.span

            if 500 <= response.status_code <= 511:
                span.mark_as_errored()

            span.set_tag(ext.HTTP_STATUS_CODE, int(response.status_code))
            tracer.inject(scope.span.context, opentracing.Format.HTTP_HEADERS, response.headers)
            response.headers.add('Server-Timing', "intid;desc=%s" % scope.span.context.trace_id)
    except:
        logger.debug("Flask after_request", exc_info=True)
    finally:
        if scope is not None:
            scope.close() 
Example #4
Source File: tornado_http.py    From opentracing-python-instrumentation with MIT License 6 votes vote down vote up
def traced_fetch_impl(real_fetch_impl):

    @functools.wraps(real_fetch_impl)
    def new_fetch_impl(self, request, callback):
        request_wrapper = TornadoRequestWrapper(request=request)
        span = before_http_request(request=request_wrapper,
                                   current_span_extractor=get_current_span)

        def new_callback(response):
            if hasattr(response, 'code') and response.code:
                span.set_tag(tags.HTTP_STATUS_CODE, '%s' % response.code)
            if hasattr(response, 'error') and response.error:
                span.set_tag(tags.ERROR, True)
                span.log(event=tags.ERROR, payload='%s' % response.error)
            span.finish()
            return callback(response)

        real_fetch_impl(self, request, new_callback)

    return new_fetch_impl 
Example #5
Source File: middleware.py    From python-sensor with MIT License 6 votes vote down vote up
def process_response(self, request, response):
        try:
            if request.iscope is not None:
                if 500 <= response.status_code <= 511:
                    request.iscope.span.assure_errored()

                request.iscope.span.set_tag(ext.HTTP_STATUS_CODE, response.status_code)
                tracer.inject(request.iscope.span.context, ot.Format.HTTP_HEADERS, response)
                response['Server-Timing'] = "intid;desc=%s" % request.iscope.span.context.trace_id

        except Exception:
            logger.debug("Instana middleware @ process_response", exc_info=True)
        finally:
            if request.iscope is not None:
                request.iscope.close()
                request.iscope = None
            return response 
Example #6
Source File: tracing.py    From python-flask with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _after_request_fn(self, response=None, error=None):
        request = stack.top.request

        # the pop call can fail if the request is interrupted by a
        # `before_request` method so we need a default
        scope = self._current_scopes.pop(request, None)
        if scope is None:
            return

        if response is not None:
            scope.span.set_tag(tags.HTTP_STATUS_CODE, response.status_code)
        if error is not None:
            scope.span.set_tag(tags.ERROR, True)
            scope.span.log_kv({
                'event': tags.ERROR,
                'error.object': error,
            })

        scope.close() 
Example #7
Source File: app_django.py    From python-sensor with MIT License 6 votes vote down vote up
def complex(request):
    with opentracing.tracer.start_active_span('asteroid') as pscope:
        pscope.span.set_tag(ext.COMPONENT, "Python simple example app")
        pscope.span.set_tag(ext.SPAN_KIND, ext.SPAN_KIND_RPC_SERVER)
        pscope.span.set_tag(ext.PEER_HOSTNAME, "localhost")
        pscope.span.set_tag(ext.HTTP_URL, "/python/simple/one")
        pscope.span.set_tag(ext.HTTP_METHOD, "GET")
        pscope.span.set_tag(ext.HTTP_STATUS_CODE, 200)
        pscope.span.log_kv({"foo": "bar"})
        time.sleep(.2)

        with opentracing.tracer.start_active_span('spacedust', child_of=pscope.span) as cscope:
            cscope.span.set_tag(ext.SPAN_KIND, ext.SPAN_KIND_RPC_CLIENT)
            cscope.span.set_tag(ext.PEER_HOSTNAME, "localhost")
            cscope.span.set_tag(ext.HTTP_URL, "/python/simple/two")
            cscope.span.set_tag(ext.HTTP_METHOD, "POST")
            cscope.span.set_tag(ext.HTTP_STATUS_CODE, 204)
            cscope.span.set_baggage_item("someBaggage", "someValue")
            time.sleep(.1)

    return HttpResponse('Stan wuz here!') 
Example #8
Source File: urllib3.py    From python-sensor with MIT License 5 votes vote down vote up
def collect_response(scope, response):
        try:
            scope.span.set_tag(ext.HTTP_STATUS_CODE, response.status)

            if hasattr(agent, 'extra_headers') and agent.extra_headers is not None:
                for custom_header in agent.extra_headers:
                    if custom_header in response.headers:
                        scope.span.set_tag("http.%s" % custom_header, response.headers[custom_header])

            if 500 <= response.status <= 599:
                scope.span.mark_as_errored()
        except Exception:
            logger.debug("collect_response", exc_info=True) 
Example #9
Source File: test_middleware.py    From python-django with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def verify_traced_tags(self):
        client = Client()
        client.get('/traced/')

        spans = settings.OPENTRACING_TRACING._tracer.finished_spans()
        assert len(spans) == 1
        assert spans[0].tags.get(tags.COMPONENT, None) == 'django'
        assert spans[0].tags.get(tags.HTTP_METHOD, None) == 'GET'
        assert spans[0].tags.get(tags.HTTP_STATUS_CODE, None) == 200
        assert spans[0].tags.get(tags.SPAN_KIND, None) == tags.SPAN_KIND_RPC_SERVER 
Example #10
Source File: tracing.py    From python-django with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _finish_tracing(self, request, response=None, error=None):
        scope = self._current_scopes.pop(request, None)
        if scope is None:
            return

        if error is not None:
            scope.span.set_tag(tags.ERROR, True)
            scope.span.log_kv({
                'event': tags.ERROR,
                'error.object': error,
            })
        if response is not None:
            scope.span.set_tag(tags.HTTP_STATUS_CODE, response.status_code)

        scope.close() 
Example #11
Source File: with_blinker.py    From python-sensor with MIT License 5 votes vote down vote up
def teardown_request_with_instana(*argv, **kwargs):
    """
    In the case of exceptions, after_request_with_instana isn't called
    so we capture those cases here.
    """
    if hasattr(flask.g, 'scope') and flask.g.scope is not None:
        if len(argv) > 0 and argv[0] is not None:
            scope = flask.g.scope
            scope.span.log_exception(argv[0])
            if ext.HTTP_STATUS_CODE not in scope.span.tags:
                scope.span.set_tag(ext.HTTP_STATUS_CODE, 500)
        flask.g.scope.close()
        flask.g.scope = None 
Example #12
Source File: vanilla.py    From python-sensor with MIT License 5 votes vote down vote up
def teardown_request_with_instana(*argv, **kwargs):
    """
    In the case of exceptions, after_request_with_instana isn't called
    so we capture those cases here.
    """
    if hasattr(flask.g, 'scope') and flask.g.scope is not None:
        if len(argv) > 0 and argv[0] is not None:
            scope = flask.g.scope
            scope.span.log_exception(argv[0])
            if ext.HTTP_STATUS_CODE not in scope.span.tags:
                scope.span.set_tag(ext.HTTP_STATUS_CODE, 500)
        flask.g.scope.close()
        flask.g.scope = None 
Example #13
Source File: span.py    From python-sensor with MIT License 5 votes vote down vote up
def _collect_http_tags(self, span):
        self.data["http"]["host"] = span.tags.pop("http.host", None)
        self.data["http"]["url"] = span.tags.pop(ot_tags.HTTP_URL, None)
        self.data["http"]["path"] = span.tags.pop("http.path", None)
        self.data["http"]["params"] = span.tags.pop('http.params', None)
        self.data["http"]["method"] = span.tags.pop(ot_tags.HTTP_METHOD, None)
        self.data["http"]["status"] = span.tags.pop(ot_tags.HTTP_STATUS_CODE, None)
        self.data["http"]["path_tpl"] = span.tags.pop("http.path_tpl", None)
        self.data["http"]["error"] = span.tags.pop('http.error', None)

        if span.operation_name == "soap":
            self.data["soap"]["action"] = span.tags.pop('soap.action', None) 
Example #14
Source File: wsgi.py    From python-sensor with MIT License 5 votes vote down vote up
def __call__(self, environ, start_response):
        env = environ

        def new_start_response(status, headers, exc_info=None):
            """Modified start response with additional headers."""
            tracer.inject(self.scope.span.context, ot.Format.HTTP_HEADERS, headers)
            headers.append(('Server-Timing', "intid;desc=%s" % self.scope.span.context.trace_id))

            res = start_response(status, headers, exc_info)

            sc = status.split(' ')[0]
            if 500 <= int(sc) <= 511:
                self.scope.span.mark_as_errored()

            self.scope.span.set_tag(tags.HTTP_STATUS_CODE, sc)
            self.scope.close()
            return res

        ctx = tracer.extract(ot.Format.HTTP_HEADERS, env)
        self.scope = tracer.start_active_span("wsgi", child_of=ctx)

        if hasattr(agent, 'extra_headers') and agent.extra_headers is not None:
            for custom_header in agent.extra_headers:
                # Headers are available in this format: HTTP_X_CAPTURE_THIS
                wsgi_header = ('HTTP_' + custom_header.upper()).replace('-', '_')
                if wsgi_header in env:
                    self.scope.span.set_tag("http.%s" % custom_header, env[wsgi_header])

        if 'PATH_INFO' in env:
            self.scope.span.set_tag('http.path', env['PATH_INFO'])
        if 'QUERY_STRING' in env and len(env['QUERY_STRING']):
            scrubbed_params = strip_secrets(env['QUERY_STRING'], agent.secrets_matcher, agent.secrets_list)
            self.scope.span.set_tag("http.params", scrubbed_params)
        if 'REQUEST_METHOD' in env:
            self.scope.span.set_tag(tags.HTTP_METHOD, env['REQUEST_METHOD'])
        if 'HTTP_HOST' in env:
            self.scope.span.set_tag("http.host", env['HTTP_HOST'])

        return self.app(environ, new_start_response) 
Example #15
Source File: webapp2_inst.py    From python-sensor with MIT License 4 votes vote down vote up
def call_with_instana(wrapped, instance, argv, kwargs):
        env = argv[0]
        start_response = argv[1]

        def new_start_response(status, headers, exc_info=None):
            """Modified start response with additional headers."""
            if 'stan_scope' in env:
                scope = env['stan_scope']
                tracer.inject(scope.span.context, ot.Format.HTTP_HEADERS, headers)
                headers.append(('Server-Timing', "intid;desc=%s" % scope.span.context.trace_id))

                res = start_response(status, headers, exc_info)

                sc = status.split(' ')[0]
                if 500 <= int(sc) <= 511:
                    scope.span.mark_as_errored()

                scope.span.set_tag(tags.HTTP_STATUS_CODE, sc)
                scope.close()
                return res
            else:
                return start_response(status, headers, exc_info)

        ctx = tracer.extract(ot.Format.HTTP_HEADERS, env)
        scope = env['stan_scope'] = tracer.start_active_span("wsgi", child_of=ctx)

        if hasattr(agent, 'extra_headers') and agent.extra_headers is not None:
            for custom_header in agent.extra_headers:
                # Headers are available in this format: HTTP_X_CAPTURE_THIS
                wsgi_header = ('HTTP_' + custom_header.upper()).replace('-', '_')
                if wsgi_header in env:
                    scope.span.set_tag("http.%s" % custom_header, env[wsgi_header])

        if 'PATH_INFO' in env:
            scope.span.set_tag('http.path', env['PATH_INFO'])
        if 'QUERY_STRING' in env and len(env['QUERY_STRING']):
            scrubbed_params = strip_secrets(env['QUERY_STRING'], agent.secrets_matcher, agent.secrets_list)
            scope.span.set_tag("http.params", scrubbed_params)
        if 'REQUEST_METHOD' in env:
            scope.span.set_tag(tags.HTTP_METHOD, env['REQUEST_METHOD'])
        if 'HTTP_HOST' in env:
            scope.span.set_tag("http.host", env['HTTP_HOST'])

        return wrapped(env, new_start_response) 
Example #16
Source File: span.py    From apm-agent-python with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def set_tag(self, key, value):
        if self.is_transaction:
            if key == "type":
                self.elastic_apm_ref.transaction_type = value
            elif key == "result":
                self.elastic_apm_ref.result = value
            elif key == tags.HTTP_STATUS_CODE:
                self.elastic_apm_ref.result = "HTTP {}xx".format(compat.text_type(value)[0])
                traces.set_context({"status_code": value}, "response")
            elif key == "user.id":
                traces.set_user_context(user_id=value)
            elif key == "user.username":
                traces.set_user_context(username=value)
            elif key == "user.email":
                traces.set_user_context(email=value)
            elif key == tags.HTTP_URL:
                traces.set_context({"url": get_url_dict(value)}, "request")
            elif key == tags.HTTP_METHOD:
                traces.set_context({"method": value}, "request")
            elif key == tags.COMPONENT:
                traces.set_context({"framework": {"name": value}}, "service")
            else:
                self.elastic_apm_ref.label(**{key: value})
        elif not self.is_dropped:
            if key.startswith("db."):
                span_context = self.elastic_apm_ref.context or {}
                if "db" not in span_context:
                    span_context["db"] = {}
                if key == tags.DATABASE_STATEMENT:
                    span_context["db"]["statement"] = value
                elif key == tags.DATABASE_USER:
                    span_context["db"]["user"] = value
                elif key == tags.DATABASE_TYPE:
                    span_context["db"]["type"] = value
                    self.elastic_apm_ref.type = "db." + value
                else:
                    self.elastic_apm_ref.label(**{key: value})
                self.elastic_apm_ref.context = span_context
            elif key == tags.SPAN_KIND:
                self.elastic_apm_ref.type = value
            else:
                self.elastic_apm_ref.label(**{key: value})
        return self 
Example #17
Source File: urllib.py    From opentracing-python-instrumentation with MIT License 4 votes vote down vote up
def install_patches():
    if six.PY3:
        # The old urllib does not exist in Py3, so delegate to urllib2 patcher
        from . import urllib2
        urllib2.install_patches()
        return

    import urllib
    import urlparse

    log.info('Instrumenting urllib methods for tracing')

    class TracedURLOpener(urllib.FancyURLopener):

        def open(self, fullurl, data=None):
            parsed_url = urlparse.urlparse(fullurl)
            host = parsed_url.hostname or None
            port = parsed_url.port or None

            span = utils.start_child_span(
                operation_name='urllib', parent=current_span_func())

            span.set_tag(ext_tags.SPAN_KIND, ext_tags.SPAN_KIND_RPC_CLIENT)

            # use span as context manager so that its finish() method is called
            with span:
                span.set_tag(ext_tags.HTTP_URL, fullurl)
                if host:
                    span.set_tag(ext_tags.PEER_HOST_IPV4, host)
                if port:
                    span.set_tag(ext_tags.PEER_PORT, port)
                # TODO add callee service name
                # TODO add headers to propagate trace
                # cannot use super here, this is an old style class
                fileobj = urllib.FancyURLopener.open(self, fullurl, data)
                if fileobj.getcode() is not None:
                    span.set_tag(ext_tags.HTTP_STATUS_CODE, fileobj.getcode())

            return fileobj

        def retrieve(self, url, filename=None, reporthook=None, data=None):
            raise NotImplementedError

    urllib._urlopener = TracedURLOpener()