Python opentracing.ext.tags.HTTP_METHOD Examples

The following are 15 code examples of opentracing.ext.tags.HTTP_METHOD(). 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: sudsjurko.py    From python-sensor with MIT License 6 votes vote down vote up
def send_with_instana(wrapped, instance, args, kwargs):
        parent_span = tracer.active_span

        # If we're not tracing, just return
        if parent_span is None:
            return wrapped(*args, **kwargs)

        with tracer.start_active_span("soap", child_of=parent_span) as scope:
            try:
                scope.span.set_tag('soap.action', instance.method.name)
                scope.span.set_tag(ext.HTTP_URL, instance.method.location)
                scope.span.set_tag(ext.HTTP_METHOD, 'POST')

                tracer.inject(scope.span.context, opentracing.Format.HTTP_HEADERS, instance.options.headers)

                rv = wrapped(*args, **kwargs)

            except Exception as e:
                scope.span.log_exception(e)
                scope.span.set_tag(ext.HTTP_STATUS_CODE, 500)
                raise
            else:
                scope.span.set_tag(ext.HTTP_STATUS_CODE, 200)
                return rv 
Example #2
Source File: tracing.py    From python-flask with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _before_request_fn(self, attributes):
        request = stack.top.request
        operation_name = request.endpoint
        headers = {}
        for k, v in request.headers:
            headers[k.lower()] = v

        try:
            span_ctx = self.tracer.extract(opentracing.Format.HTTP_HEADERS,
                                           headers)
            scope = self.tracer.start_active_span(operation_name,
                                                  child_of=span_ctx)
        except (opentracing.InvalidCarrierException,
                opentracing.SpanContextCorruptedException):
            scope = self.tracer.start_active_span(operation_name)

        self._current_scopes[request] = scope

        span = scope.span
        span.set_tag(tags.COMPONENT, 'Flask')
        span.set_tag(tags.HTTP_METHOD, request.method)
        span.set_tag(tags.HTTP_URL, request.base_url)
        span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_SERVER)

        for attr in attributes:
            if hasattr(request, attr):
                payload = getattr(request, attr)
                if payload not in ('', b''):  # python3
                    span.set_tag(attr, str(payload))

        self._call_start_span_cb(span, request) 
Example #3
Source File: test_flask_tracing.py    From python-flask with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_span_tags(self):
        test_app.get('/another_test_simple')

        spans = tracing._tracer.finished_spans()
        assert len(spans) == 1
        assert spans[0].tags == {
            tags.COMPONENT: 'Flask',
            tags.HTTP_METHOD: 'GET',
            tags.SPAN_KIND: tags.SPAN_KIND_RPC_SERVER,
            tags.HTTP_URL: 'http://localhost/another_test_simple',
            'is_xhr': 'False',
        } 
Example #4
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 #5
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 #6
Source File: vanilla.py    From python-sensor with MIT License 5 votes vote down vote up
def before_request_with_instana(*argv, **kwargs):
    try:
        env = flask.request.environ
        ctx = None

        if 'HTTP_X_INSTANA_T' in env and 'HTTP_X_INSTANA_S' in env:
            ctx = tracer.extract(opentracing.Format.HTTP_HEADERS, env)

        flask.g.scope = tracer.start_active_span('wsgi', child_of=ctx)
        span = flask.g.scope.span

        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
                header = ('HTTP_' + custom_header.upper()).replace('-', '_')
                if header in env:
                    span.set_tag("http.%s" % custom_header, env[header])

        span.set_tag(ext.HTTP_METHOD, flask.request.method)
        if 'PATH_INFO' in env:
            span.set_tag(ext.HTTP_URL, 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)
            span.set_tag("http.params", scrubbed_params)
        if 'HTTP_HOST' in env:
            span.set_tag("http.host", env['HTTP_HOST'])

        if hasattr(flask.request.url_rule, 'rule') and \
                path_tpl_re.search(flask.request.url_rule.rule) is not None:
            path_tpl = flask.request.url_rule.rule.replace("<", "{")
            path_tpl = path_tpl.replace(">", "}")
            span.set_tag("http.path_tpl", path_tpl)
    except:
        logger.debug("Flask before_request", exc_info=True)
    finally:
        return None 
Example #7
Source File: with_blinker.py    From python-sensor with MIT License 5 votes vote down vote up
def request_started_with_instana(sender, **extra):
    try:
        env = flask.request.environ
        ctx = None

        if 'HTTP_X_INSTANA_T' in env and 'HTTP_X_INSTANA_S' in env:
            ctx = tracer.extract(opentracing.Format.HTTP_HEADERS, env)

        flask.g.scope = tracer.start_active_span('wsgi', child_of=ctx)
        span = flask.g.scope.span

        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
                header = ('HTTP_' + custom_header.upper()).replace('-', '_')
                if header in env:
                    span.set_tag("http.%s" % custom_header, env[header])

        span.set_tag(ext.HTTP_METHOD, flask.request.method)
        if 'PATH_INFO' in env:
            span.set_tag(ext.HTTP_URL, 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)
            span.set_tag("http.params", scrubbed_params)
        if 'HTTP_HOST' in env:
            span.set_tag("http.host", env['HTTP_HOST'])

        if hasattr(flask.request.url_rule, 'rule') and \
                path_tpl_re.search(flask.request.url_rule.rule) is not None:
            path_tpl = flask.request.url_rule.rule.replace("<", "{")
            path_tpl = path_tpl.replace(">", "}")
            span.set_tag("http.path_tpl", path_tpl)
    except:
        logger.debug("Flask before_request", exc_info=True) 
Example #8
Source File: urllib3.py    From python-sensor with MIT License 5 votes vote down vote up
def urlopen_with_instana(wrapped, instance, args, kwargs):
        parent_span = tracer.active_span

        # If we're not tracing, just return
        if parent_span is None:
            return wrapped(*args, **kwargs)

        with tracer.start_active_span("urllib3", child_of=parent_span) as scope:
            try:
                kvs = collect(instance, args, kwargs)
                if 'url' in kvs:
                    scope.span.set_tag(ext.HTTP_URL, kvs['url'])
                if 'query' in kvs:
                    scope.span.set_tag("http.params", kvs['query'])
                if 'method' in kvs:
                    scope.span.set_tag(ext.HTTP_METHOD, kvs['method'])

                if 'headers' in kwargs:
                    tracer.inject(scope.span.context, opentracing.Format.HTTP_HEADERS, kwargs['headers'])

                response = wrapped(*args, **kwargs)

                collect_response(scope, response)

                return response
            except Exception as e:
                scope.span.mark_as_errored({'message': e})
                raise 
Example #9
Source File: app.py    From microservices-in-action with MIT License 5 votes vote down vote up
def get_user_settings(uuid):
    logger.info("getting user settings", extra={"uuid": uuid})
    settings_url = urljoin("http://settings:5000/settings/", "{}".format(uuid))

    span = get_current_span()
    span.set_tag(tags.HTTP_METHOD, 'GET')
    span.set_tag(tags.HTTP_URL, settings_url)
    span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_CLIENT)
    span.set_tag('uuid', uuid)
    headers = {}
    tracer.inject(span, Format.HTTP_HEADERS, headers)

    r = requests.get(settings_url, headers=headers)
    return r.json() 
Example #10
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 #11
Source File: tweens.py    From python-sensor with MIT License 4 votes vote down vote up
def __call__(self, request):
        ctx = tracer.extract(ot.Format.HTTP_HEADERS, request.headers)        
        scope = tracer.start_active_span('http', child_of=ctx)

        scope.span.set_tag(ext.SPAN_KIND, ext.SPAN_KIND_RPC_SERVER)
        scope.span.set_tag("http.host", request.host)
        scope.span.set_tag(ext.HTTP_METHOD, request.method)
        scope.span.set_tag(ext.HTTP_URL, request.path)

        if request.matched_route is not None:
            scope.span.set_tag("http.path_tpl", request.matched_route.pattern)

        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
                h = ('HTTP_' + custom_header.upper()).replace('-', '_')
                if h in request.headers:
                    scope.span.set_tag("http.%s" % custom_header, request.headers[h])

        if len(request.query_string):
            scrubbed_params = strip_secrets(request.query_string, agent.secrets_matcher, agent.secrets_list)
            scope.span.set_tag("http.params", scrubbed_params)

        response = None
        try:
            response = self.handler(request)
            
            tracer.inject(scope.span.context, ot.Format.HTTP_HEADERS, response.headers)
            response.headers['Server-Timing'] = "intid;desc=%s" % scope.span.context.trace_id
        except HTTPException as e:
            response = e
            raise
        except BaseException as e:
            scope.span.set_tag("http.status", 500)

            # we need to explicitly populate the `message` tag with an error here
            # so that it's picked up from an SDK span
            scope.span.set_tag("message", str(e))            
            scope.span.log_exception(e)
            
            logger.debug("Pyramid Instana tween", exc_info=True)
        finally:
            if response:
                scope.span.set_tag("http.status", response.status_int)
                
                if 500 <= response.status_int <= 511:
                    if response.exception is not None:
                        message = str(response.exception)
                        scope.span.log_exception(response.exception)
                    else:
                        message = response.status
                        
                    scope.span.set_tag("message", message)
                    scope.span.assure_errored()

            scope.close()

        return response 
Example #12
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 #13
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 #14
Source File: http_server.py    From opentracing-python-instrumentation with MIT License 4 votes vote down vote up
def before_request(request, tracer=None):
    """
    Attempts to extract a tracing span from incoming request.
    If no tracing context is passed in the headers, or the data
    cannot be parsed, a new root span is started.

    :param request: HTTP request with `.headers` property exposed
        that satisfies a regular dictionary interface
    :param tracer: optional tracer instance to use. If not specified
        the global opentracing.tracer will be used.
    :return: returns a new, already started span.
    """
    if tracer is None:
        tracer = opentracing.tracer

    # we need to prepare tags upfront, mainly because RPC_SERVER tag must be
    # set when starting the span, to support Zipkin's one-span-per-RPC model
    tags_dict = {
        tags.SPAN_KIND: tags.SPAN_KIND_RPC_SERVER,
        tags.HTTP_URL: request.full_url,
        tags.HTTP_METHOD: request.method,
    }

    remote_ip = request.remote_ip
    if remote_ip:
        tags_dict[tags.PEER_HOST_IPV4] = remote_ip

    caller_name = request.caller_name
    if caller_name:
        tags_dict[tags.PEER_SERVICE] = caller_name

    remote_port = request.remote_port
    if remote_port:
        tags_dict[tags.PEER_PORT] = remote_port

    operation = request.operation
    try:
        carrier = {}
        for key, value in six.iteritems(request.headers):
            carrier[key] = value
        parent_ctx = tracer.extract(
            format=Format.HTTP_HEADERS, carrier=carrier
        )
    except Exception as e:
        logging.exception('trace extract failed: %s' % e)
        parent_ctx = None

    span = tracer.start_span(
        operation_name=operation,
        child_of=parent_ctx,
        tags=tags_dict)

    return span 
Example #15
Source File: tracing.py    From python-django with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _apply_tracing(self, request, view_func, attributes):
        '''
        Helper function to avoid rewriting for middleware and decorator.
        Returns a new span from the request with logged attributes and
        correct operation name from the view_func.
        '''
        # strip headers for trace info
        headers = {}
        for k, v in six.iteritems(request.META):
            k = k.lower().replace('_', '-')
            if k.startswith('http-'):
                k = k[5:]
            headers[k] = v

        # start new span from trace info
        operation_name = view_func.__name__
        try:
            span_ctx = self.tracer.extract(opentracing.Format.HTTP_HEADERS,
                                           headers)
            scope = self.tracer.start_active_span(operation_name,
                                                  child_of=span_ctx)
        except (opentracing.InvalidCarrierException,
                opentracing.SpanContextCorruptedException):
            scope = self.tracer.start_active_span(operation_name)

        # add span to current spans
        self._current_scopes[request] = scope

        # standard tags
        scope.span.set_tag(tags.COMPONENT, 'django')
        scope.span.set_tag(tags.SPAN_KIND, tags.SPAN_KIND_RPC_SERVER)
        scope.span.set_tag(tags.HTTP_METHOD, request.method)
        scope.span.set_tag(tags.HTTP_URL, request.get_full_path())

        # log any traced attributes
        for attr in attributes:
            if hasattr(request, attr):
                payload = str(getattr(request, attr))
                if payload:
                    scope.span.set_tag(attr, payload)

        # invoke the start span callback, if any
        self._call_start_span_cb(scope.span, request)

        return scope