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 Zipkin Laravel Package

auxmoney/opentracing-bundle-zipkin

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install Dependencies:

    composer require auxmoney/opentracing-bundle-zipkin auxmoney/opentracing-bundle-core
    

    Ensure auxmoney/opentracing-bundle-core is installed as it provides the base functionality.

  2. Enable the Bundle: Add to config/bundles.php:

    return [
        // ...
        Auxmoney\OpentracingBundle\AuxmoneyOpentracingBundle::class => ['all' => true],
        Auxmoney\OpentracingBundle\Zipkin\ZipkinBundle::class => ['all' => true],
    ];
    
  3. Configure Zipkin Reporter: Add to config/packages/auxmoney_opentracing.yaml:

    auxmoney_opentracing:
        tracer:
            reporter:
                class: Zipkin\Reporters\Http\JsonHttpReporter
                options:
                    endpoint: 'http://zipkin-server:9411/api/v2/spans'
    
  4. First Use Case: Inject the tracer into a service and start a span:

    use OpenTracing\Tracer;
    
    class MyService {
        public function __construct(private Tracer $tracer) {}
    
        public function doWork() {
            $span = $this->tracer->buildSpan('my-operation')->start();
            try {
                // Business logic here
            } finally {
                $span->finish();
            }
        }
    }
    

Implementation Patterns

Core Workflows

  1. Request Tracing: Automatically trace incoming HTTP requests by leveraging Symfony’s event system:

    auxmoney_opentracing:
        http:
            enabled: true
            headers:
                trace_id: 'X-B3-TraceId'
                span_id: 'X-B3-SpanId'
    
  2. Sampling Strategies: Configure sampling to balance performance and observability:

    auxmoney_opentracing:
        sampler:
            class: Zipkin\Samplers\PercentageSampler
            value: '0.1'  # Sample 10% of requests
    
  3. Custom Span Context: Propagate trace context across services (e.g., HTTP clients):

    $spanContext = $this->tracer->extract(
        \OpenTracing\FORMAT_HTTP_HEADERS,
        $requestHeaders
    );
    $span = $this->tracer->buildSpan('external-call')->withTaggedContext($spanContext)->start();
    
  4. Integration with HTTP Clients: Use the HttpSpan decorator for automatic span creation in HTTP calls:

    $client = new HttpSpan($this->tracer, $httpClient);
    $response = $client->request('GET', 'https://api.example.com');
    

Advanced Patterns

  • Dynamic Configuration: Override sampler or reporter settings dynamically via environment variables:

    export AUXMONEY_OPENTRACING_SAMPLER_CLASS="Zipkin\Samplers\ProbabilitySampler"
    export AUXMONEY_OPENTRACING_SAMPLER_VALUE="0.5"
    
  • Custom Tags: Add context-specific tags to spans:

    $span->setTag('user.id', $userId);
    $span->setTag('http.method', $request->getMethod());
    
  • Error Tracking: Log exceptions with stack traces:

    try {
        // Risky operation
    } catch (\Exception $e) {
        $span->setTag('error', true);
        $span->log(['event' => 'error', 'message' => $e->getMessage()]);
        throw $e;
    }
    

Gotchas and Tips

Common Pitfalls

  1. Sampler Misconfiguration:

    • Issue: Using BinarySampler with false disables all tracing.
    • Fix: Verify sampler class and value in config/packages/auxmoney_opentracing.yaml or environment variables.
  2. Zipkin Server Unreachable:

    • Issue: Spans fail to report if the Zipkin endpoint is down.
    • Fix: Implement a fallback reporter or buffer spans locally:
      auxmoney_opentracing:
          tracer:
              reporter:
                  class: Zipkin\Reporters\InMemoryReporter
      
  3. Header Propagation:

    • Issue: Trace IDs not propagated across microservices.
    • Fix: Ensure headers (X-B3-TraceId, X-B3-SpanId) are included in outgoing requests:
      $headers['X-B3-TraceId'] = $span->context()->toTraceId();
      $headers['X-B3-SpanId'] = $span->context()->toSpanId();
      
  4. Performance Overhead:

    • Issue: High sampling rates degrade performance.
    • Fix: Use PercentageSampler or ProbabilitySampler to limit tracing:
      auxmoney_opentracing:
          sampler:
              class: Zipkin\Samplers\ProbabilitySampler
              value: '0.01'  # 1% sampling
      

Debugging Tips

  • Validate Spans: Use Zipkin’s UI to verify spans are being recorded. Check for:

    • Missing spans (sampler issue).
    • Incomplete context (header propagation issue).
  • Log Configuration: Enable debug logging for the bundle:

    monolog:
        handlers:
            main:
                level: debug
                channels: ["auxmoney_opentracing"]
    
  • Environment-Specific Config: Use separate configs for dev/staging/prod to avoid over-tracing in production:

    # config/packages/dev/auxmoney_opentracing.yaml
    auxmoney_opentracing:
        sampler:
            class: Zipkin\Samplers\BinarySampler
            value: 'true'  # Always sample in dev
    

Extension Points

  1. Custom Reporters: Extend Zipkin\Reporter to implement custom reporting logic (e.g., async batching):

    class AsyncHttpReporter implements Reporter {
        public function report(Span $span) {
            // Queue spans for async processing
        }
    }
    
  2. Sampler Plugins: Create custom samplers (e.g., rate-limiting based on request path):

    class PathBasedSampler implements Sampler {
        public function isSampled(Reference $parent = null) {
            $request = RequestStack::getCurrentRequest();
            return str_starts_with($request->getPathInfo(), '/admin');
        }
    }
    
  3. Span Decorators: Wrap existing spans to add metadata or validate data:

    class ValidatingSpanDecorator implements Span {
        private Span $span;
    
        public function __construct(Span $span) {
            $this->span = $span;
        }
    
        public function setTag($key, $value) {
            if ($key === 'user.id' && !is_numeric($value)) {
                throw new \InvalidArgumentException("Invalid user ID");
            }
            $this->span->setTag($key, $value);
        }
    }
    
  4. Event Listeners: Hook into Symfony events to start/finish spans automatically:

    // src/EventListener/TracingListener.php
    class TracingListener {
        public function onKernelRequest(GetResponseEvent $event) {
            $span = $this->tracer->buildSpan('http.request')->start();
            $event->getRequest()->attributes->set('tracing.span', $span);
        }
    
        public function onKernelException(ExceptionEvent $event) {
            $span = $event->getRequest()->attributes->get('tracing.span');
            $span->setTag('error', true);
            $span->finish();
        }
    }
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui