Jaeger PHP Client

repository·master·Indexed 41 days ago

https://github.com/jonahgeorge/jaeger-client-php

A client-side library for PHP that implements the OpenTracing API to instrument applications for distributed tracing and send data to Jaeger. It supports multiple dispatch modes including Zipkin over Compact UDP, Jaeger over Binary UDP, and Jaeger over Binary HTTP, as well as various sampling strategies like Const, Probabilistic, and Rate Limiting samplers.

Tokens
7K
Snippets
29
Records
33
Agent score
100%

What's inside Jaeger PHP Client

  1. Configure Samplers

    master

    Samplers determine which requests are traced. The following sampler types are supported via the sampler configuration key:

    Const Sampler

    Traces everything or nothing based on a boolean parameter.

    • type: Jaeger\SAMPLER_TYPE_CONST
    • param: true (trace) or false (don't trace)

    Probabilistic Sampler

    Traces requests based on a given rate.

    • type: Jaeger\SAMPLER_TYPE_PROBABILISTIC
    • param: A float between 0.0 and 1.0.

    Rate Limiting Sampler

    Traces a maximum number of requests per second. Requirements:

    • A psr/cache (PSR-6) implementation passed to the Config constructor.
    • PHP 7.3+ or the PECL/hrtime extension.
    • type: Jaeger\SAMPLER_TYPE_RATE_LIMITING
    • param: An integer representing max traces per second.
    • cache: An array containing currentBalanceKey and lastTickKey (strings) to store state.
    // Const Sampler Example
    'sampler' => [
        'type' => Jaeger\SAMPLER_TYPE_CONST,
        'param' => true,
    ],
    
    // Probabilistic Sampler Example
    'sampler' => [
        'type' => Jaeger\SAMPLER_TYPE_PROBABILISTIC,
        'param' => 0.5,
    ],
    
    // Rate Limiting Sampler Example
    'sampler' => [
        'type' => Jaeger\SAMPLER_TYPE_RATE_LIMITING,
        'param' => 100,
        'cache' => [
            'currentBalanceKey' => 'rate.currentBalance',
            'lastTickKey' => 'rate.lastTick'
        ]
    ],
  2. Get started with Jaeger instrumentation

    master

    To use the library, create a Jaeger\Config object with your desired settings (including a sampler), call initializeTracer() to set up the global tracer, and then use the OpenTracing\GlobalTracer to manage spans. Always remember to call $tracer->flush() to ensure pending spans are sent to the Jaeger agent.

    <?php
    
    require_once 'vendor/autoload.php';
    
    use Jaeger\Config;
    use OpenTracing\GlobalTracer;
    
    $config = new Config(
        [
            'sampler' => [
                'type' => Jaeger\SAMPLER_TYPE_CONST,
                'param' => true,
            ],
            'logging' => true,
        ],
        'your-app-name'
    );
    $config->initializeTracer();
    
    $tracer = GlobalTracer::get();
    
    $scope = $tracer->startActiveSpan('TestSpan', []);
    $scope->close();
    
    $tracer->flush();
  3. Configure Tags and Local Agent

    master

    When configuring the Jaeger\Config, you can define global tags and local agent connection details:

    • tags: An associative array of tags. Tags with the process. prefix (e.g., process.my-key) are assigned to the process section (only supported with JAEGER_OVER_HTTP or JAEGER_OVER_BINARY). Other tags are appended to all spans.
    • local_agent: An array to configure the agent connection:
      • reporting_host: The hostname of the Jaeger agent (default: localhost).
      • reporting_port: The port of the Jaeger agent.
    // config.php
    return [
        'sampler' => [
            'type' => Jaeger\SAMPLER_TYPE_CONST,
            'param' => true,
        ],
        'logging' => true,
        'tags' => [
            'process.process-tag-key-1' => 'process-value-1',
            'global-tag-key-1' => 'global-tag-value-1',
        ],
        'local_agent' => [
            'reporting_host' => 'localhost',
            'reporting_port' => 6832
        ],
        'dispatch_mode' => Jaeger\Config::JAEGER_OVER_BINARY_UDP,
    ];
  4. Configure Dispatch Mode

    master

    The library supports three ways to send data to the Jaeger Agent. You can set the dispatch_mode in the configuration array or use the JAEGER_DISPATCH_MODE environment variable. It is recommended to use the constants provided in the Jaeger\Config class.

    ConstantValueProtocolDefault Port
    Config::ZIPKIN_OVER_COMPACT_UDPzipkin_over_compact_udpZipkin.thrift (Compact) over UDP5775
    Config::JAEGER_OVER_BINARY_UDPjaeger_over_binary_udpJaeger.thrift (Binary) over UDP6832
    Config::JAEGER_OVER_BINARY_HTTPjaeger_over_binary_httpJaeger.thrift (Binary) over HTTP14268
    use Jaeger\Config;
    
    $config = [
        'dispatch_mode' => Config::JAEGER_OVER_BINARY_UDP,
        // ... other config
    ];
  5. Initialize the Jaeger tracer using Config

    master

    To start tracing in your application, instantiate the Jaeger\Config class with a configuration array and then call initializeTracer(). This method creates the tracer, sets it as the OpenTracing\GlobalTracer, and returns the Tracer instance.

    Note that service_name is a required configuration key or constructor parameter.

    use Jaeger\Config;
    
    $configArray = [
        'service_name' => 'my-service',
        'dispatch_mode' => 'jaeger_over_binary_udp',
        'local_agent' => [
            'reporting_host' => '127.0.0.1',
            'reporting_port' => 6831,
        ],
    ];
    
    $config = new Config($configArray);
    $tracer = $config->initializeTracer();
  6. Enable IPv6 support

    master

    By default, the library uses IPv4. To enable IPv6, set the ip_version key in your configuration to Jaeger\Config::IPV6. You can use the string key ip_version or the constant Jaeger\Config::IP_VERSION.

    use Jaeger\Config;
    
    $config = new Config(
        [
            "ip_version" => Config::IPV6,
            'logging' => true,
            'dispatch_mode' => Config::JAEGER_OVER_BINARY_UDP,
        ],
        'serviceNameExample',
    );
    $config->initializeTracer();
  7. Add metadata using setTag()

    master

    Use setTag(string $key, $value) to attach metadata to a span. The Span class handles several 'special' tags by mapping them to specific internal structures for better compatibility with Jaeger/Zipkin:

    • OpenTracing\Tags\COMPONENT: Sets the module/library identifier.
    • OpenTracing\Tags\PEER_SERVICE: Sets the service name of the peer.
    • OpenTracing\Tags\PEER_HOST_IPV4: Sets the peer's IPv4 address.
    • OpenTracing\Tags\PEER_PORT: Sets the peer's port.
    • OpenTracing\Tags\SPAN_KIND: Sets the span kind (e.g., RPC_CLIENT, RPC_SERVER, MESSAGE_BUS_CONSUMER, MESSAGE_BUS_PRODUCER).

    For all other keys, the value is converted into a BinaryAnnotation with an appropriate type (BOOL, I64, DOUBLE, or STRING).

    // Example of setting various tags
    $span->setTag(OpenTracing\Tags\COMPONENT, 'my-library');
    $span->setTag(OpenTracing\Tags\PEER_SERVICE, 'auth-service');
    $span->setTag('custom.key', 'custom.value');
  8. Manage baggage items

    master

    Baggage items are key-value pairs that are propagated across span contexts. Use addBaggageItem(string $key, string $value) to add an item and getBaggageItem(string $key) to retrieve it.

    Note that adding baggage items updates the underlying SpanContext.

    $span->addBaggageItem('user_id', '12345');
    $userId = $span->getBaggageItem('user_id'); // returns '12345'
  9. Finish a span and report it

    master

    Call finish($finishTime = null, array $logRecords = []) to mark the end of a unit of work.

    • If the span is not sampled, finish() does nothing.
    • If sampled, it sets the end time and triggers the tracer to report the span.
    • You can pass an optional $finishTime (matching the types accepted by log()) and an array of $logRecords to be processed before finishing.
    // Standard usage
    $span->finish();
    
    // Finishing with a specific time and extra logs
    $span->finish(microtime(true), [['event' => 'cleanup']]);
  10. Record events using log()

    master

    Use log(array $fields = [], $timestamp = null) to record timestamped events or logs within a span. This is useful for capturing errors or specific state changes.

    • $fields: An associative array of key-value pairs representing the log data.
    • $timestamp: An optional timestamp. It accepts int (microseconds), float (seconds), or DateTimeInterface. If omitted, the current time is used.

    Logs are stored as an array of entries, each containing a timestamp and the fields provided.

    // Log an error event
    $span->log(['error' => 'database connection failed'], new DateTime());
    
    // Log a simple event
    $span->log(['event' => 'cache_miss']);
  11. Use JaegerSender to transmit spans

    master

    The Jaeger//Sender//JaegerSender class is responsible for collecting spans and transmitting them to a Jaeger collector via a Thrift agent client.

    To use it, you must provide an implementation of Jaeger\Thrift\Agent\AgentIf (the agent client). You can optionally provide a PSR-3 compatible LoggerInterface and a SpanToJaegerMapper during construction.

    Workflow:

    1. Append Spans: Use append(JaegerSpan $span) to add spans to the internal buffer.
    2. Flush Spans: Use flush() to trigger the transmission of all buffered spans to the Jaeger agent. This method returns the number of spans successfully processed.
    3. Close: The close() method is available to satisfy the SenderInterface but currently performs no action.
    use Jaeger//Sender//JaegerSender;
    use Jaeger//Thrift//Agent//AgentClient;
    
    // Assuming $agentClient is an instance of AgentIf
    $sender = new JaegerSender($agentClient);
    
    // Add a span to the buffer
    $sender->append($span);
    
    // Send buffered spans to the collector
    $count = $sender->flush();