jaeger-client-python

repository·master·Indexed 19 days ago

https://github.com/jaegertracing/jaeger-client-python

A client-side library for Python that provides Jaeger bindings for the OpenTracing API, used to instrument applications for distributed trace collection. It includes support for Prometheus metrics, Zipkin B3 propagation compatibility, and guidance on tracer initialization for production, asyncio, and multi-processing environments.

Tokens
2.6K
Snippets
10
Records
11
Agent score
15%

What's inside jaeger-client-python

  1. Force sampling for debug traces

    master

    You can force a trace to be sampled using two methods:

    1. Programmatically: Set the sampling.priority tag on a span.
    2. Via HTTP Headers: Include the jaeger-debug-id header in an incoming request. This ensures the trace is sampled in 'debug' mode and the root span is tagged with the provided ID, allowing you to find it in the Jaeger UI.
    # Programmatic approach
    from opentracing.ext import tags as ext_tags
    span.set_tag(ext_tags.SAMPLING_PRIORITY, 1)
    # HTTP Header approach
    curl -H "jaeger-debug-id: some-correlation-id" http://myhost.com
  2. Get started with jaeger-client

    master

    To use the library, configure a Config object, initialize the tracer, and use it to create spans. Note that config.initialize_tracer() also sets the global opentracing.tracer variable. Always ensure you call tracer.close() to flush buffered spans before the application exits.

    import logging
    import time
    from jaeger_client import Config
    
    if __name__ == "__main__":
        log_level = logging.DEBUG
        logging.getLogger('').handlers = []
        logging.basicConfig(format='%(asctime)s %(message)s', level=log_level)
    
        config = Config(
            config={
                'sampler': {
                    'type': 'const',
                    'param': 1,
                },
                'logging': True,
            },
            service_name='your-app-name',
            validate=True,
        )
        # this call also sets opentracing.tracer
        tracer = config.initialize_tracer()
    
        with tracer.start_span('TestSpan') as span:
            span.log_kv({'event': 'test message', 'life': 42})
    
            with tracer.start_span('ChildSpan', child_of=span) as child_span:
                child_span.log_kv({'event': 'down below'})
    
        time.sleep(2)   # yield to IOLoop to flush the spans
        tracer.close()  # flush any buffered spans
  3. Initialize the tracer for production

    master

    The recommended pattern for production is to wrap initialization in a function. initialize_tracer() sets the global opentracing.tracer. If you need to create additional tracers for remote services, use the new_tracer() method.

    from jaeger_client import Config
    
    def init_jaeger_tracer(service_name='your-app-name'):
        config = Config(config={}, service_name=service_name, validate=True)
        return config.initialize_tracer()
  4. Initialize the tracer correctly to avoid deadlocks

    master

    Do not initialize the tracer during module import, as this may cause a deadlock. Instead, define a function that returns a tracer and call it explicitly after all imports are completed.

    If using gevent.monkey in asyncio-based applications (Python 3+), you may need to pass the current event loop explicitly to initialize_tracer.

    from tornado import ioloop
    from jaeger_client import Config
    
    config = Config(config={}, service_name='your-app-name', validate=True)
    config.initialize_tracer(io_loop=ioloop.IOLoop.current())
  5. Configure reporting host and port

    master

    If running Jaeger in a separate container (e.g., using the all-in-one Docker image), you can specify the remote agent's location using the local_agent configuration key. Note that Jaeger sends spans over UDP, which does not guarantee delivery.

        config = Config(
            config={
                'sampler': {
                    'type': 'const',
                    'param': 1,
                },
                'local_agent': {
                    'reporting_host': 'your-reporting-host',
                    'reporting_port': 'your-reporting-port',
                },
                'logging': True,
            },
            service_name='your-app-name',
            validate=True,
        })
  6. Handle tracer initialization in WSGI and multi-processing

    master
    In applications that fork child processes (like WSGI/PEP 3333), initializing the tracer in the parent process can cause hangs or issues due to background threads and interpreter locks. It is recommended to delay tracer initialization until after the child processes have been forked (e.g., using a @postfork decorator).
  7. Enable Prometheus metrics for Jaeger client

    master

    You can integrate Prometheus metrics by using the PrometheusMetricsFactory. This allows you to monitor internal Jaeger client metrics. Use the service_name_label argument to tag metrics with a specific service name, making it easier to distinguish metrics from different services.

    from jaeger_client.metrics.prometheus import PrometheusMetricsFactory
    
    config = Config(
            config={},
            service_name='your-app-name',
            validate=True,
            metrics_factory=PrometheusMetricsFactory(service_name_label='your-app-name')
    )
    tracer = config.initialize_tracer()
  8. Configure Crossdock environment variables

    master

    The crossdock service uses several environment variables to control the behavior of the cross-language testing suite. These variables define timeouts, client types, service names, transport protocols, and trace behaviors.

    Core Configuration

    • WAIT_FOR: Comma-separated list of services to wait for before starting (e.g., test_driver,go,python,java,nodejs).
    • WAIT_FOR_TIMEOUT: Timeout duration for the wait period (e.g., 60s).
    • CALL_TIMEOUT: Timeout for calls (e.g., 60s).
    • AXIS_CLIENT: Specifies the client type (e.g., go).
    • AXIS_TESTDRIVER: Specifies the test driver service (e.g., test_driver).
    • AXIS_SERVICES: Specifies the services to be tested (e.g., python).
    • REPORT: Reporting format (e.g., compact).

    Axis Configuration

    These variables define the parameters for the Axis testing logic:

    • AXIS_S1NAME: Comma-separated list of service names for S1 (e.g., go,python,java,nodejs).
    • AXIS_S1TRANSPORT: (Implicitly used via S1 configuration).
    • AXIS_SAMPLED: Comma-separated list of sampling booleans (e.g., true,false).
    • AXIS_S2NAME: Comma-separated list of service names for S2 (e.g., go,python,java,nodejs).
    • AXIS_S2TRANSPORT: Transport protocol for S2 (e.g., http).
    • AXIS_S3NAME: Comma-separated list of service names for S3 (e.g., go,python,java,nodejs).
    • AXIS_S3TRANSPORT: Transport protocol for S3 (e.g., http).

    Behavior Configuration

    • BEHAVIOR_TRACE: Defines the trace behavior pattern (e.g., client,s1name,sampled,s2name,s2transport,s3name,s3transport).
    • BEHAVIOR_ENDTOEND: Defines the end-to-end behavior pattern (e.g., testdriver,services).
    services:
      crossdock:
        environment:
          - WAIT_FOR=test_driver,go,python,java,nodejs
          - WAIT_FOR_TIMEOUT=60s
          - CALL_TIMEOUT=60s
          - AXIS_CLIENT=go
          - AXIS_S1NAME=go,python,java,nodejs
          - AXIS_SAMPLED=true,false
          - AXIS_S2NAME=go,python,java,nodejs
          - AXIS_S2TRANSPORT=http
          - AXIS_S3NAME=go,python,java,nodejs
          - AXIS_S3TRANSPORT=http
          - BEHAVIOR_TRACE=client,s1name,sampled,s2name,s2transport,s3name,s3transport
          - AXIS_TESTDRIVER=test_driver
          - AXIS_SERVICES=python
          - BEHAVIOR_ENDTOEND=testdriver,services
          - REPORT=compact
  9. Configure Jaeger All-in-One environment variables

    master

    The jaeger service (using the jaegertracing/all-in-one image) can be configured via environment variables:

    • COLLECTOR_ZIPKIN_HTTP_PORT: Sets the port for the Zipkin collector compatibility (e.g., 9411).
    • LOG_LEVEL: Sets the logging verbosity (e.g., debug).
    jeager:
      image: jaegertracing/all-in-one
      environment:
        - COLLECTOR_ZIPKIN_HTTP_PORT=9411
        - LOG_LEVEL=debug