How to use the opencensus.trace.span.SpanKind function in opencensus

To help you get started, we’ve selected a few opencensus examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github census-instrumentation / opencensus-python / tests / unit / trace / ext / sqlalchemy / test_sqlalchemy_trace.py View on Github external
parameters = 'test'

        with patch:
            trace._before_cursor_execute(None, None, query,
                                         parameters, None, False)

        expected_attributes = {
            'sqlalchemy.query': query,
            'sqlalchemy.query.parameters': parameters,
            'sqlalchemy.cursor.method.name': 'execute'
        }

        expected_name = 'sqlalchemy.query'

        self.assertEqual(mock_tracer.current_span.span_kind,
                         span_module.SpanKind.CLIENT)
        self.assertEqual(mock_tracer.current_span.attributes,
                         expected_attributes)
        self.assertEqual(mock_tracer.current_span.name, expected_name)
github census-instrumentation / opencensus-python / tests / unit / trace / exporters / ocagent / test_trace_exporter_utils.py View on Github external
def test_translate_client_span_kind(self):
        client_span_data = span_data_module.SpanData(
            context=span_context_module.SpanContext(
                trace_id='6e0c63257de34c92bf9efcd03927272e'),
            span_id='6e0c63257de34c92',
            start_time='2017-08-15T18:02:26.071158Z',
            end_time='2017-08-15T18:02:36.071158Z',
            span_kind=span_module.SpanKind.CLIENT,
            same_process_as_parent_span=True,
            name=None,
            parent_span_id=None,
            attributes=None,
            child_span_count=None,
            stack_trace=None,
            time_events=None,
            links=None,
            status=None)

        pb_span = utils.translate_to_trace_proto(client_span_data)

        self.assertEqual(pb_span.kind, 2)
        self.assertEqual(pb_span.same_process_as_parent_span.value, True)
github census-instrumentation / opencensus-python / tests / unit / trace / ext / grpc / test_server_interceptor.py View on Github external
with self.assertRaises(Exception):
                    getattr(handler, rpc_fn_name)(mock.Mock(), mock_context)

            expected_attributes = {
                'component': 'grpc',
                'error.message': 'Test'
            }

            current_span = execution_context.get_opencensus_tracer(
            ).current_span()
            self.assertEqual(
                execution_context.get_opencensus_tracer().current_span().
                attributes, expected_attributes)

            self.assertEqual(current_span.span_kind,
                             span_module.SpanKind.SERVER)

            # check that the stack trace is attached to the current span
            self.assertIsNotNone(current_span.stack_trace)
            self.assertIsNotNone(current_span.stack_trace.stack_trace_hash_id)
            self.assertNotEqual(current_span.stack_trace.stack_frames, [])

            # check that the status obj is attached to the current span
            self.assertIsNotNone(current_span.status)
            self.assertEqual(current_span.status.code, code_pb2.UNKNOWN)
            self.assertEqual(current_span.status.message, 'Test')
github census-instrumentation / opencensus-python / contrib / opencensus-ext-django / opencensus / ext / django / middleware.py View on Github external
def _trace_db_call(execute, sql, params, many, context):
    tracer = _get_current_tracer()
    if not tracer:
        return execute(sql, params, many, context)

    vendor = context['connection'].vendor
    alias = context['connection'].alias

    span = tracer.start_span()
    span.name = '{}.query'.format(vendor)
    span.span_kind = span_module.SpanKind.CLIENT

    tracer.add_attribute_to_current_span('component', vendor)
    tracer.add_attribute_to_current_span('db.instance', alias)
    tracer.add_attribute_to_current_span('db.statement', sql)
    tracer.add_attribute_to_current_span('db.type', 'sql')

    try:
        result = execute(sql, params, many, context)
    except Exception:  # pragma: NO COVER
        status = status_module.Status(
            code=code_pb2.UNKNOWN, message='DB error'
        )
        span.set_status(status)
        raise
    else:
        return result
github forseti-security / forseti-security / google / cloud / forseti / common / opencensus / tracing.py View on Github external
"""Start a span.

    Args:
        tracer (opencensus.trace.tracer.Tracer): OpenCensus tracer object.
        module (str): The module name.
        function (str): The function name.
        kind (opencensus.trace.span.SpanKind): The span kind.
            Default: `SpanKind.SERVER`.
    """
    if tracer is None:
        LOGGER.debug('No tracer found, cannot do `start_span`.')
        return

    span_name = '[{}] {}'.format(module, function)
    span = tracer.start_span(name=span_name)
    span.span_kind = kind or SpanKind.SERVER
    set_span_attributes(tracer, module=module, function=function)
    LOGGER.debug('%s.%s: %s', module, function, tracer.span_context)
github census-instrumentation / opencensus-python / contrib / opencensus-ext-postgresql / opencensus / ext / postgresql / trace.py View on Github external
def call(query, *args, **kwargs):
        _tracer = execution_context.get_opencensus_tracer()
        if _tracer is not None:
            # Note that although get_opencensus_tracer() returns a NoopTracer
            # if no thread local has been set, set_opencensus_tracer() does NOT
            # protect against setting None to the thread local - be defensive
            # here
            _span = _tracer.start_span()
            _span.name = '{}.query'.format(MODULE_NAME)
            _span.span_kind = span_module.SpanKind.CLIENT
            _tracer.add_attribute_to_current_span(
                '{}.query'.format(MODULE_NAME), query)
            _tracer.add_attribute_to_current_span(
                '{}.cursor.method.name'.format(MODULE_NAME),
                query_func.__name__)

        result = query_func(query, *args, **kwargs)

        if _tracer is not None:
            _tracer.end_span()
        return result
github census-instrumentation / opencensus-python / contrib / opencensus-ext-pyramid / opencensus / ext / pyramid / pyramid_middleware.py View on Github external
span_context = self.propagator.from_headers(request.headers)

            tracer = tracer_module.Tracer(
                span_context=span_context,
                sampler=self.sampler,
                exporter=self.exporter,
                propagator=self.propagator)

            span = tracer.start_span()

            # Set the span name as the name of the current module name
            span.name = '[{}]{}'.format(
                request.method,
                request.path)

            span.span_kind = span_module.SpanKind.SERVER
            tracer.add_attribute_to_current_span(
                attribute_key=HTTP_HOST,
                attribute_value=request.host_url)
            tracer.add_attribute_to_current_span(
                attribute_key=HTTP_METHOD,
                attribute_value=request.method)
            tracer.add_attribute_to_current_span(
                attribute_key=HTTP_PATH,
                attribute_value=request.path)
            tracer.add_attribute_to_current_span(
                attribute_key=HTTP_ROUTE,
                attribute_value=request.path)
            tracer.add_attribute_to_current_span(
                attribute_key=HTTP_URL,
                attribute_value=request.url)
        except Exception:  # pragma: NO COVER
github Azure / azure-sdk-for-python / sdk / core / azure-core / azure / core / tracing / ext / opencensus_span.py View on Github external
def set_http_attributes(self, request, response=None):
        # type: (HttpRequest, Optional[HttpResponse]) -> None
        """
        Add correct attributes for a http client span.

        :param request: The request made
        :type request: HttpRequest
        :param response: The response received by the server. Is None if no response received.
        :type response: HttpResponse
        """
        self._span_instance.span_kind = SpanKind.CLIENT
        self.span_instance.add_attribute(self._span_component, "http")
        self.span_instance.add_attribute(self._http_method, request.method)
        self.span_instance.add_attribute(self._http_url, request.url)
        user_agent = request.headers.get("User-Agent")
        if user_agent:
            self.span_instance.add_attribute(self._http_user_agent, user_agent)
        if response:
            self._span_instance.add_attribute(self._http_status_code, response.status_code)
        else:
            self._span_instance.add_attribute(self._http_status_code, 504)
github census-instrumentation / opencensus-python / contrib / opencensus-ext-django / opencensus / ext / django / middleware.py View on Github external
try:
            # Start tracing this request
            span_context = self.propagator.from_headers(
                _DjangoMetaWrapper(_get_django_request().META))

            # Reload the tracer with the new span context
            tracer = tracer_module.Tracer(
                span_context=span_context,
                sampler=self.sampler,
                exporter=self.exporter,
                propagator=self.propagator)

            # Span name is being set at process_view
            span = tracer.start_span()
            span.span_kind = span_module.SpanKind.SERVER
            tracer.add_attribute_to_current_span(
                attribute_key=HTTP_HOST,
                attribute_value=request.get_host())
            tracer.add_attribute_to_current_span(
                attribute_key=HTTP_METHOD,
                attribute_value=request.method)
            tracer.add_attribute_to_current_span(
                attribute_key=HTTP_PATH,
                attribute_value=str(request.path))
            tracer.add_attribute_to_current_span(
                attribute_key=HTTP_ROUTE,
                attribute_value=str(request.path))
            tracer.add_attribute_to_current_span(
                attribute_key=HTTP_URL,
                attribute_value=str(request.build_absolute_uri()))
github census-instrumentation / opencensus-python / contrib / opencensus-ext-httplib / opencensus / ext / httplib / trace.py View on Github external
def call(self, method, url, body, headers, *args, **kwargs):
        # Check if request was sent from an exporter. If so, do not wrap.
        if execution_context.is_exporter():
            return request_func(self, method, url, body,
                                headers, *args, **kwargs)
        _tracer = execution_context.get_opencensus_tracer()
        blacklist_hostnames = execution_context.get_opencensus_attr(
            'blacklist_hostnames')
        dest_url = '{}:{}'.format(self.host, self.port)
        if utils.disable_tracing_hostname(dest_url, blacklist_hostnames):
            return request_func(self, method, url, body,
                                headers, *args, **kwargs)
        _span = _tracer.start_span()
        _span.span_kind = span_module.SpanKind.CLIENT
        _span.name = '[httplib]{}'.format(request_func.__name__)

        # Add the request url to attributes
        _tracer.add_attribute_to_current_span(HTTP_URL, url)

        # Add the request method to attributes
        _tracer.add_attribute_to_current_span(HTTP_METHOD, method)

        # Store the current span id to thread local.
        execution_context.set_opencensus_attr(
            'httplib/current_span_id', _span.span_id)
        try:
            headers = headers.copy()
            headers.update(_tracer.propagator.to_headers(
                _span.context_tracer.span_context))
        except Exception:  # pragma: NO COVER