Python opentracing.Tracer() Examples

The following are 30 code examples of opentracing.Tracer(). 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 , or try the search function .
Example #1
Source File: tracing.py    From community-playground with Apache License 2.0 6 votes vote down vote up
def incoming_trace(operation: str, request: Request,
                   tracer: Tracer) -> Generator[Span, None, None]:
    span_context = tracer.extract(
        format=Format.HTTP_HEADERS,carrier=dict(request.headers))

    params = {}
    if span_context:
        params["child_of"] = span_context
    with tracer.start_span(operation, **params) as span:
        span.set_tag('http.url', request.url)

        remote_ip = request.client.host
        if remote_ip:
            span.set_tag(tags.PEER_HOST_IPV4, remote_ip)

        remote_port = request.client.port
        if remote_port:
            span.set_tag(tags.PEER_PORT, remote_port)

        yield span 
Example #2
Source File: test_noop_tracer.py    From jaeger-client-python with Apache License 2.0 6 votes vote down vote up
def test_new_trace():
    tracer = Tracer()

    span = tracer.start_span(operation_name='test')
    span.set_baggage_item('Fry', 'Leela')
    span.set_tag('x', 'y')
    span.log_event('z')

    child = tracer.start_span(operation_name='child',
                              references=opentracing.child_of(span.context))
    child.log_event('w')
    assert child.get_baggage_item('Fry') is None
    carrier = {}
    tracer.inject(
        span_context=child.context,
        format=Format.TEXT_MAP,
        carrier=carrier)
    assert carrier == dict()
    child.finish()

    span.finish() 
Example #3
Source File: test_noop_tracer.py    From jaeger-client-python with Apache License 2.0 6 votes vote down vote up
def test_join_trace():
    tracer = Tracer()

    span_ctx = tracer.extract(format=Format.TEXT_MAP, carrier={})
    span = tracer.start_span(operation_name='test',
                             references=opentracing.child_of(span_ctx))
    span.set_tag('x', 'y')
    span.set_baggage_item('a', 'b')
    span.log_event('z')

    child = tracer.start_span(operation_name='child',
                              references=opentracing.child_of(span.context))
    child.log_event('w')
    child.finish()

    span.finish() 
Example #4
Source File: tracing.py    From community-playground with Apache License 2.0 6 votes vote down vote up
def init_jaeger_tracer() -> Tracer:
    config = Config(
        config={
            'sampler': {
                'type': 'const',
                'param': 1,
            },
            'logging': True,
            'propagation': "b3",
            'local_agent': {
                'reporting_host': 'localhost'
            }
        },
        service_name='service2',
        validate=True,
        scope_manager=AsyncioScopeManager()
    )
    return config.initialize_tracer() 
Example #5
Source File: tracing.py    From community-playground with Apache License 2.0 6 votes vote down vote up
def incoming_trace(operation: str, request: Request,
                   tracer: Tracer) -> Generator[Span, None, None]:
    span_context = tracer.extract(
        format=Format.HTTP_HEADERS,carrier=dict(request.headers))

    params = {}
    if span_context:
        params["child_of"] = span_context
    with tracer.start_span(operation, **params) as span:
        span.set_tag('http.url', request.url)

        remote_ip = request.client.host
        if remote_ip:
            span.set_tag(tags.PEER_HOST_IPV4, remote_ip)

        remote_port = request.client.port
        if remote_port:
            span.set_tag(tags.PEER_PORT, remote_port)

        yield span 
Example #6
Source File: tracing.py    From community-playground with Apache License 2.0 6 votes vote down vote up
def init_jaeger_tracer() -> Tracer:
    config = Config(
        config={
            'sampler': {
                'type': 'const',
                'param': 1,
            },
            'logging': True,
            'propagation': "b3",
            'local_agent': {
                'reporting_host': 'localhost'
            }
        },
        service_name='service2',
        validate=True,
        scope_manager=AsyncioScopeManager()
    )
    return config.initialize_tracer() 
Example #7
Source File: tracing.py    From community-playground with Apache License 2.0 6 votes vote down vote up
def incoming_trace(operation: str, request: Request,
                   tracer: Tracer) -> Generator[Span, None, None]:
    span_context = tracer.extract(
        format=Format.HTTP_HEADERS,carrier=dict(request.headers))
    print(request.headers, flush=True)
    print(span_context, flush=True)

    params = {}
    if span_context:
        params["child_of"] = span_context
    with tracer.start_span(operation, **params) as span:
        span.set_tag('http.url', request.url)

        remote_ip = request.client.host
        if remote_ip:
            span.set_tag(tags.PEER_HOST_IPV4, remote_ip)

        remote_port = request.client.port
        if remote_port:
            span.set_tag(tags.PEER_PORT, remote_port)

        yield span 
Example #8
Source File: __init__.py    From opentelemetry-python with Apache License 2.0 6 votes vote down vote up
def create_tracer(otel_tracer_provider):
    """Creates a :class:`TracerShim` object from the provided OpenTelemetry
    :class:`opentelemetry.trace.TracerProvider`.

    The returned :class:`TracerShim` is an implementation of
    :class:`opentracing.Tracer` using OpenTelemetry under the hood.

    Args:
        otel_tracer_provider: A :class:`opentelemetry.trace.TracerProvider` to be
            used for constructing the :class:`TracerShim`. A tracer from this
            source will be used to perform the actual tracing when user code is
            instrumented using the OpenTracing API.

    Returns:
        The created :class:`TracerShim`.
    """

    return TracerShim(otel_tracer_provider.get_tracer(__name__, __version__)) 
Example #9
Source File: tracing.py    From community-playground with Apache License 2.0 6 votes vote down vote up
def init_jaeger_tracer() -> Tracer:
    config = Config(
        config={
            'sampler': {
                'type': 'const',
                'param': 1,
            },
            'logging': True,
            'propagation': "b3",
            'local_agent': {
                'reporting_host': 'localhost'
            }
        },
        service_name='service2',
        validate=True,
        scope_manager=AsyncioScopeManager()
    )
    return config.initialize_tracer() 
Example #10
Source File: tracing.py    From community-playground with Apache License 2.0 6 votes vote down vote up
def init_jaeger_tracer() -> Tracer:
    config = Config(
        config={
            'sampler': {
                'type': 'const',
                'param': 1,
            },
            'logging': True,
            'propagation': "b3",
            'local_agent': {
                'reporting_host': 'localhost'
            }
        },
        service_name='service2',
        validate=True,
        scope_manager=AsyncioScopeManager()
    )
    return config.initialize_tracer() 
Example #11
Source File: tracing.py    From community-playground with Apache License 2.0 6 votes vote down vote up
def init_jaeger_tracer() -> Tracer:
    config = Config(
        config={
            'sampler': {
                'type': 'const',
                'param': 1,
            },
            'logging': True,
            'propagation': "b3",
            'local_agent': {
                'reporting_host': 'localhost'
            }
        },
        service_name='service1',
        validate=True,
        scope_manager=ThreadLocalScopeManager()
    )
    return config.initialize_tracer() 
Example #12
Source File: tracing.py    From community-playground with Apache License 2.0 6 votes vote down vote up
def incoming_trace(operation: str, request: Request,
                   tracer: Tracer) -> Generator[Span, None, None]:
    span_context = tracer.extract(
        format=Format.HTTP_HEADERS,carrier=dict(request.headers))

    params = {}
    if span_context:
        params["child_of"] = span_context
    with tracer.start_span(operation, **params) as span:
        span.set_tag('http.url', request.url)

        remote_ip = request.client.host
        if remote_ip:
            span.set_tag(tags.PEER_HOST_IPV4, remote_ip)

        remote_port = request.client.port
        if remote_port:
            span.set_tag(tags.PEER_PORT, remote_port)

        yield span 
Example #13
Source File: test_noop_span.py    From opentracing-python with Apache License 2.0 6 votes vote down vote up
def test_inject():
    tracer = Tracer()
    span = tracer.start_span()

    bin_carrier = bytearray()
    tracer.inject(
        span_context=span.context,
        format=Format.BINARY,
        carrier=bin_carrier)
    assert bin_carrier == bytearray()

    text_carrier = {}
    tracer.inject(
        span_context=span.context,
        format=Format.TEXT_MAP,
        carrier=text_carrier)
    assert text_carrier == {} 
Example #14
Source File: test_noop_span.py    From opentracing-python with Apache License 2.0 6 votes vote down vote up
def test_span_error_report():
    tracer = Tracer()
    span = tracer.start_span('foo')
    error_message = 'unexpected_situation'

    with mock.patch.object(span, 'log_kv') as log_kv:
        with mock.patch.object(span, 'set_tag') as set_tag:
            try:
                with span:
                    raise ValueError(error_message)
            except ValueError:
                pass

            assert set_tag.call_count == 1
            assert set_tag.call_args[0] == (tags.ERROR, True)

            assert log_kv.call_count == 1
            log_kv_args = log_kv.call_args[0][0]
            assert log_kv_args.get(logs.EVENT, None) is tags.ERROR
            assert log_kv_args.get(logs.MESSAGE, None) is error_message
            assert log_kv_args.get(logs.ERROR_KIND, None) is ValueError
            assert isinstance(log_kv_args.get(logs.ERROR_OBJECT, None),
                              ValueError)
            assert isinstance(log_kv_args.get(logs.STACK, None),
                              types.TracebackType) 
Example #15
Source File: tracing.py    From community-playground with Apache License 2.0 6 votes vote down vote up
def init_jaeger_tracer() -> Tracer:
    config = Config(
        config={
            'sampler': {
                'type': 'const',
                'param': 1,
            },
            'logging': True,
            'propagation': "b3",
            'local_agent': {
                'reporting_host': 'localhost'
            }
        },
        service_name='service1',
        validate=True,
        scope_manager=AsyncioScopeManager()
    )
    return config.initialize_tracer() 
Example #16
Source File: tracing.py    From community-playground with Apache License 2.0 6 votes vote down vote up
def outgoing_trace(operation: str, request: Request, tracer: Tracer,
                   parent: Span) \
                       -> Generator[Tuple[Span, Dict[str, Any]], None, None]:
    with tracer.start_span(operation, child_of=parent) as span:
        span.set_tag('http.url', request.url)

        remote_ip = request.client.host
        if remote_ip:
            span.set_tag(tags.PEER_HOST_IPV4, remote_ip)

        remote_port = request.client.port
        if remote_port:
            span.set_tag(tags.PEER_PORT, remote_port)

        http_header_carrier = {}
        tracer.inject(
            span_context=span,
            format=Format.HTTP_HEADERS,
            carrier=http_header_carrier
        )

        yield (span, http_header_carrier) 
Example #17
Source File: tracing.py    From community-playground with Apache License 2.0 6 votes vote down vote up
def init_jaeger_tracer() -> Tracer:
    config = Config(
        config={
            'sampler': {
                'type': 'const',
                'param': 1,
            },
            'logging': True,
            'propagation': "b3",
            'local_agent': {
                'reporting_host': 'localhost'
            }
        },
        service_name='service1',
        validate=True,
        scope_manager=AsyncioScopeManager()
    )
    return config.initialize_tracer() 
Example #18
Source File: tracing.py    From community-playground with Apache License 2.0 6 votes vote down vote up
def incoming_trace(operation: str, request: Request,
                   tracer: Tracer) -> Generator[Span, None, None]:
    span_context = tracer.extract(
        format=Format.HTTP_HEADERS,carrier=dict(request.headers))

    params = {}
    if span_context:
        params["child_of"] = span_context
    with tracer.start_span(operation, **params) as span:
        span.set_tag('http.url', request.url)

        remote_ip = request.client.host
        if remote_ip:
            span.set_tag(tags.PEER_HOST_IPV4, remote_ip)

        remote_port = request.client.port
        if remote_port:
            span.set_tag(tags.PEER_PORT, remote_port)

        yield span 
Example #19
Source File: tracing.py    From community-playground with Apache License 2.0 6 votes vote down vote up
def outgoing_trace(operation: str, request: Request, tracer: Tracer,
                   parent: Span) \
                       -> Generator[Tuple[Span, Dict[str, Any]], None, None]:
    with tracer.start_span(operation, child_of=parent) as span:
        span.set_tag('http.url', request.url)

        remote_ip = request.client.host
        if remote_ip:
            span.set_tag(tags.PEER_HOST_IPV4, remote_ip)

        remote_port = request.client.port
        if remote_port:
            span.set_tag(tags.PEER_PORT, remote_port)

        http_header_carrier = {}
        tracer.inject(
            span_context=span,
            format=Format.HTTP_HEADERS,
            carrier=http_header_carrier
        )

        yield span, http_header_carrier 
Example #20
Source File: test_noop_tracer.py    From opentracing-python with Apache License 2.0 5 votes vote down vote up
def test_tracer_active_span():
    tracer = Tracer()
    assert tracer.active_span is tracer.scope_manager.active.span 
Example #21
Source File: test_tracer_benchmark.py    From jaeger-client-python with Apache License 2.0 5 votes vote down vote up
def test_noop_tracer(benchmark):
    tracer = NoopTracer()
    benchmark(_generate_spans, tracer) 
Example #22
Source File: tracer.py    From jaeger-client-python with Apache License 2.0 5 votes vote down vote up
def start_active_span(self,
                          operation_name=None,
                          child_of=None,
                          references=None,
                          tags=None,
                          start_time=None,
                          ignore_active_span=False,
                          finish_on_close=True,
                          ):
        """
        Returns a newly started and activated :class:`Scope`

        :param operation_name: name of the operation represented by the new
            span from the perspective of the current service.
        :param child_of: shortcut for 'child_of' reference
        :param references: (optional) either a single Reference object or a
            list of Reference objects that identify one or more parent
            SpanContexts. (See the Reference documentation for detail)
        :param tags: optional dictionary of Span Tags. The caller gives up
            ownership of that dictionary, because the Tracer may use it as-is
            to avoid extra data copying.
        :param start_time: an explicit Span start time as a unix timestamp per
            time.time()
        :param ignore_active_span: an explicit flag that ignores the current
            active :class:`Scope` and creates a root :class:`Span`
        :param finish_on_close: whether :class:`Span` should automatically be
            finished when :meth:`Scope.close()` is called.

        :return: a :class:`Scope`, already registered via the :class:`ScopeManager`.
        """
        span = self.start_span(
            operation_name=operation_name,
            child_of=child_of,
            references=references,
            tags=tags,
            start_time=start_time,
            ignore_active_span=ignore_active_span,
        )
        return self.scope_manager.activate(span, finish_on_close) 
Example #23
Source File: test_shim.py    From opentelemetry-python with Apache License 2.0 5 votes vote down vote up
def test_shim_type(self):
        # Verify shim is an OpenTracing tracer.
        self.assertIsInstance(self.shim, opentracing.Tracer) 
Example #24
Source File: __init__.py    From opentelemetry-python with Apache License 2.0 5 votes vote down vote up
def unwrap(self):
        """Returns the :class:`opentelemetry.trace.Tracer` object that is
        wrapped by this :class:`TracerShim` and used for actual tracing.

        Returns:
            The :class:`opentelemetry.trace.Tracer` used for actual tracing.
        """

        return self._otel_tracer 
Example #25
Source File: __init__.py    From opentelemetry-python with Apache License 2.0 5 votes vote down vote up
def from_context_manager(cls, manager, span_cm):
        """Constructs a :class:`ScopeShim` from an OpenTelemetry
        `opentelemetry.trace.Span` context
        manager.

        The method extracts a `opentelemetry.trace.Span` object from the
        context manager by calling the context manager's ``__enter__()``
        method. This causes the span to start in the OpenTelemetry tracer.

        Example usage::

            span = otel_tracer.start_span("TestSpan")
            span_cm = otel_tracer.use_span(span)
            scope_shim = ScopeShim.from_context_manager(
                scope_manager_shim,
                span_cm=span_cm,
            )

        Args:
            manager: The :class:`ScopeManagerShim` that created this
                :class:`ScopeShim`.
            span_cm: A context manager as returned by
                :meth:`opentelemetry.trace.Tracer.use_span`.
        """

        otel_span = span_cm.__enter__()
        span_context = SpanContextShim(otel_span.get_context())
        span = SpanShim(manager.tracer, span_context, otel_span)
        return cls(manager, span, span_cm) 
Example #26
Source File: _tracer.py    From python-grpc with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        super(Tracer, self).__init__()
        self._counter = 0
        self._spans = {}
        self._relationships = defaultdict(lambda: None) 
Example #27
Source File: tracer.py    From pyms with GNU General Public License v3.0 5 votes vote down vote up
def init_lightstep_tracer(self):
        check_package_exists("lightstep")
        lightstep = import_package("lightstep")
        return lightstep.Tracer(component_name=self.component_name) 
Example #28
Source File: tracer.py    From pyms with GNU General Public License v3.0 5 votes vote down vote up
def init_jaeger_tracer(self):
        """This scaffold is configured whith `Jeager <https://github.com/jaegertracing/jaeger>`_ but you can use
        one of the `opentracing tracers <http://opentracing.io/documentation/pages/supported-tracers.html>`_
        :param service_name: the name of your application to register in the tracer
        :return: opentracing.Tracer
        """
        check_package_exists("jaeger_client")
        Config = import_from("jaeger_client", "Config")
        host = {}
        if self.host:
            host = {
                'local_agent': {
                    'reporting_host': self.host
                }
            }
        metrics_config = get_conf(service=get_service_name(service="metrics"), empty_init=True)
        metrics = ""
        if metrics_config:
            service_name = self.component_name.lower().replace("-", "_").replace(" ", "_")
            metrics = PrometheusMetricsFactory(service_name_label=service_name)
        config = Config(
            config={
                **{
                    'sampler': {
                        'type': 'const',
                        'param': 1,
                    },
                    'propagation': 'b3',
                    'logging': True
                },
                **host
            }, service_name=self.component_name,
            metrics_factory=metrics,
            validate=True
        )
        return config.initialize_tracer() 
Example #29
Source File: test_flask_api.py    From python-flask with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_tracer(self):
        tracer = opentracing.Tracer()
        tracing = FlaskTracing(tracer)
        assert tracing.tracer is tracer
        assert tracing.tracer is tracing._tracer
        assert tracing._trace_all_requests is False 
Example #30
Source File: test_noop_span.py    From opentracing-python with Apache License 2.0 5 votes vote down vote up
def test_extract():
    tracer = Tracer()
    noop_span = tracer._noop_span

    bin_carrier = bytearray()
    span_ctx = tracer.extract(Format.BINARY, carrier=bin_carrier)
    assert noop_span.context == span_ctx

    text_carrier = {}
    span_ctx = tracer.extract(Format.TEXT_MAP, carrier=text_carrier)
    assert noop_span.context == span_ctx