Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Opentracing Bundle Core Laravel Package

auxmoney/opentracing-bundle-core

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require auxmoney/opentracing-bundle-core
    

    Enable it in config/bundles.php:

    return [
        // ...
        Auxmoney\OpentracingBundle\OpentracingBundle::class => ['all' => true],
    ];
    
  2. Configuration Define a tracer in config/packages/opentracing.yaml:

    opentracing:
        tracer:
            type: 'jaeger' # or 'zipkin', 'datadog', etc.
            options:
                agent_host: 'localhost'
                agent_port: 6831
    
  3. First Use Case Trigger a traced request by accessing a route or running a console command. The bundle auto-instruments HTTP requests and console commands, creating root spans with metadata like:

    • Request method/URI (for HTTP)
    • Command name/arguments (for console)

Implementation Patterns

Auto-Instrumentation

  • HTTP Requests: The bundle automatically traces incoming requests via KernelEvents::REQUEST and KernelEvents::RESPONSE. Root spans include tags like http.method, http.url, and http.status_code.

    // Example: Manually adding a custom tag
    $this->get('opentracing.tracer')->getActiveSpan()->setTag('custom.tag', 'value');
    
  • Console Commands: Commands are traced via ConsoleEvents::COMMAND and ConsoleEvents::TERMINATE. Root spans include command name, arguments, and exit code.

    // Example: Tracing a custom command
    use Auxmoney\OpentracingBundle\Tracing\TracerAwareInterface;
    
    class MyCommand extends Command implements TracerAwareInterface {
        public function handle(TracerInterface $tracer) {
            $span = $tracer->startSpan('my-command-logic');
            // ... business logic ...
            $span->finish();
        }
    }
    

Manual Span Management

  • Creating Child Spans:

    $parentSpan = $this->get('opentracing.tracer')->getActiveSpan();
    $childSpan = $this->get('opentracing.tracer')->startSpan('child-operation', ['child_of' => $parentSpan]);
    
  • Logging Messages:

    $span->log(['event' => 'user.created', 'user_id' => 123]);
    
  • Tagging Spans:

    $span->setTag('db.instance', 'primary');
    $span->setTag('span.kind', 'server');
    

PSR-18 Client Integration

The bundle auto-instruments PSR-18 HTTP clients (e.g., Symfony’s HttpClient) to propagate tracing headers. No manual setup required for supported clients.

Middleware Integration

Extend existing middleware to add tracing context:

use Auxmoney\OpentracingBundle\Tracing\TracerAwareInterface;

class MyMiddleware implements TracerAwareInterface {
    public function handle(Request $request, callable $next, TracerInterface $tracer) {
        $span = $tracer->startSpan('middleware.process');
        $response = $next($request);
        $span->finish();
        return $response;
    }
}

Gotchas and Tips

Pitfalls

  1. Tracer Initialization Order: Ensure the OpentracingBundle is loaded before any services that depend on the tracer. Use preload: true in config/bundles.php if needed:

    OpentracingBundle::class => ['all' => true, 'preload' => true],
    
  2. Circular Dependencies: Avoid circular references when manually creating spans (e.g., Span A starts Span B, which starts Span A again). Use TracerInterface::getActiveSpan() carefully.

  3. Span Leaks: Always call $span->finish() to avoid memory leaks. Use a finally block or a decorator pattern for cleanup:

    $span = $tracer->startSpan('operation');
    try {
        // Work
    } finally {
        $span->finish();
    }
    
  4. Header Propagation: If using custom PSR-18 clients, ensure they support the opentracing middleware. Fallback to manual header injection:

    $headers = $tracer->extract(Format::HTTP_HEADERS, $_SERVER);
    $client->withHeaders($headers)->request(...);
    

Debugging

  • Enable Debug Mode: Set OPENTRACING_DEBUG: true in your environment to log tracer events to Symfony’s logger:

    opentracing:
        debug: '%kernel.debug%'
    
  • Check Active Span: Inspect the active span in middleware/commands:

    $activeSpan = $tracer->getActiveSpan();
    if ($activeSpan) {
        $activeSpan->log(['debug' => 'Inspecting active span']);
    }
    

Extension Points

  1. Custom Event Subscribers: Extend tracing for custom events (e.g., Doctrine events) by implementing TracerAwareInterface:

    class MySubscriber implements TracerAwareInterface {
        public function postLoad(LifecycleEventArgs $args, TracerInterface $tracer) {
            $span = $tracer->startSpan('entity.load');
            // ...
        }
    }
    
  2. Custom Span Context: Add context to spans using tags or baggage:

    $span->setBaggageItem('user.id', '42');
    $span->setTag('component', 'auth-service');
    
  3. Dynamic Tracer Configuration: Override the tracer dynamically (e.g., per-environment):

    # config/packages/dev/opentracing.yaml
    opentracing:
        tracer:
            type: 'jaeger'
            options:
                agent_host: 'jaeger.dev.local'
    

Performance Tips

  • Batch Logging: For high-throughput services, batch span logs instead of logging per-operation:
    $span->log(['events' => [$event1, $event2]]);
    
  • Span Reuse: Reuse spans for related operations (e.g., database queries within a request span).
  • Sampling: Configure the tracer to sample spans (e.g., sampler: 'const') to reduce overhead:
    opentracing:
        tracer:
            sampler: 'const'
            sampler_options:
                sampling_rate: 0.1 # 10% sampling
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware