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

Otel Bundle Laravel Package

cyberclick-tech/otel-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cyberclick/otel-bundle
    

    Register the bundle in config/bundles.php:

    Cyberclick\OtelBundle\CyberclickOtelBundle::class => ['all' => true],
    
  2. Configure Environment Variables (.env):

    OTEL_SERVICE_NAME=myapp
    OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
    
  3. First Use Case:

    • HTTP Request Tracing: Automatically enabled for all incoming HTTP requests. Verify by sending a request and checking your OpenTelemetry backend for spans with http.method, http.route, and http.status_code attributes.

Implementation Patterns

Core Workflow

  1. Automatic Instrumentation:

    • HTTP Requests: Spans are created automatically for incoming requests. No manual setup required.
    • Console Commands: Spans are created for all console commands with exit codes.
    • Logging Correlation: Logs are automatically correlated with traces via trace_id and span_id in Monolog.
  2. Explicit Instrumentation:

    • HTTP Client: Decorate Symfony's HttpClient to trace outgoing requests:
      # config/services.yaml
      Cyberclick\OtelBundle\HttpClient\TracingHttpClient:
          decorates: http_client
          arguments:
              $client: '@.inner'
              $tracer: '@cyberclick_otel.tracer'
      
    • Doctrine: Add the middleware to your DBAL connection:
      doctrine:
          dbal:
              connections:
                  default:
                      middlewares:
                          - 'Cyberclick\OtelBundle\Doctrine\TracingMiddleware'
      
    • Messenger: Add the tracing middleware to your Messenger bus:
      framework:
          messenger:
              buses:
                  command.bus:
                      middleware:
                          - cyberclick_otel.messenger.tracing_middleware
      
  3. Manual Span Management:

    • Use MessageTracerInterface for RabbitMQ consumers:
      public function consume(string $queueName, string $body): void
      {
          $this->tracer->start($queueName, $body);
          try {
              // Process message
              $this->tracer->end('OK');
          } catch (\Throwable $e) {
              $this->tracer->registerError($e);
              $this->tracer->end('KO');
          }
      }
      

Integration Tips

  • Custom Attributes: Implement SpanAttributeExtractorInterface to add application-specific attributes (e.g., tenant ID, user ID) to spans:

    use Cyberclick\OtelBundle\SpanAttributeExtractorInterface;
    use Symfony\Component\HttpFoundation\Request;
    
    final class MyAppSpanAttributeExtractor implements SpanAttributeExtractorInterface
    {
        public function fromRequest(Request $request): array
        {
            return ['tenant.id' => $request->get('tenantId')];
        }
    
        public function fromMessageBody(?string $body): array
        {
            return ['tenant.id' => json_decode($body)?->tenant_id];
        }
    }
    

    Register it in services.yaml:

    Actel\Shared\Infrastructure\OpenTelemetry\MyAppSpanAttributeExtractor: ~
    Cyberclick\OtelBundle\SpanAttributeExtractorInterface:
        alias: Actel\Shared\Infrastructure\OpenTelemetry\MyAppSpanAttributeExtractor
    
  • Service IDs: Leverage provided services like cyberclick_otel.tracer or cyberclick_otel.messenger.tracing_middleware directly in your code.


Gotchas and Tips

Pitfalls

  1. Namespace Changes:

    • If upgrading from cyberclick-tech/otel-bundle, update all use statements and service references from CyberclickTech\OtelBundle to Cyberclick\OtelBundle.
    • Update composer.json to use cyberclick/otel-bundle.
  2. Symfony Version Compatibility:

    • Ensure your Symfony version (7.x or 8.x) matches the bundle's requirements. Symfony 6.4 is no longer supported.
  3. Doctrine Middleware:

    • If using a custom EntityManagerFactory, manually inject and set the TracingMiddleware in the DBAL\Configuration:
      $dbalConfig->setMiddlewares([$tracingMiddleware]);
      
  4. Log Correlation:

    • Ensure Monolog is configured to use the trace_id and span_id processors. The bundle automatically injects these, but verify your Monolog setup includes the Cyberclick\OtelBundle\Monolog\TraceIdProcessor.

Debugging

  • Missing Spans:

    • Verify OTEL_EXPORTER_OTLP_ENDPOINT is correctly set and the OpenTelemetry Collector is running.
    • Check for errors in Symfony's debug logs (var/log/dev.log) or the Collector's logs.
  • Doctrine Tracing:

    • If SQL spans are missing, ensure the TracingMiddleware is properly added to your DBAL connection or EntityManagerFactory.
  • HTTP Client Tracing:

    • If outgoing HTTP calls aren't traced, confirm the TracingHttpClient decorator is correctly configured in services.yaml and the target client (e.g., http_client or a scoped client like http_client.catastro) matches the decorator's name.

Tips

  1. Environment-Specific Config:

    • Use different OTEL_EXPORTER_OTLP_ENDPOINT values for development, staging, and production. Example:
      # .env.dev
      OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
      
      # .env.prod
      OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector.prod.example.com:4318
      
  2. Span Naming Conventions:

    • Customize span names for clarity. For example, override the default HTTP span name in your SpanAttributeExtractorInterface:
      public function fromRequest(Request $request): array
      {
          return [
              'http.route' => 'custom.route.name',
              // other attributes...
          ];
      }
      
  3. Performance Impact:

    • Monitor the performance overhead of tracing, especially for high-throughput endpoints. Use OpenTelemetry's sampling feature if needed (configure via OTEL_TRACES_SAMPLER environment variable).
  4. Testing:

    • Mock the cyberclick_otel.tracer service in unit tests to avoid real tracing calls:
      $this->container->set('cyberclick_otel.tracer', $this->createMock(TracerInterface::class));
      
  5. Extension Points:

    • Extend the bundle by implementing interfaces like SpanAttributeExtractorInterface or creating custom middleware for unsupported components (e.g., Symfony UX, API Platform).
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope