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

auxmoney/opentracing-bundle-monolog

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Prerequisite: Install the core auxmoney/opentracing-bundle-core first via:
    composer require auxmoney/opentracing-bundle-core
    
  2. Add Monolog Extension:
    composer require auxmoney/opentracing-bundle-monolog
    
    • For Symfony Flex, the bundle auto-enables. For manual setups, add to bundles.php:
      Auxmoney\OpentracingMonologBundle\OpentracingMonologBundle::class => ['all' => true],
      

First Use Case

Log a message with OpenTracing context automatically injected:

$this->logger->info('Processing payment', [
    'amount' => 100,
    'currency' => 'EUR'
]);

Output (JSON-encoded in logs):

{"opentracing-context":"{\"UBER-TRACE-ID\":\"12345:67890:1:2\"}"}

Key Files to Review

  • config/packages/monolog.yaml (if customizing log handlers)
  • src/Logger/Processor/OpenTracingProcessor.php (core logic)

Implementation Patterns

Core Workflow

  1. Span Context Injection: The bundle adds a Monolog Processor that attaches the current OpenTracing span context to every log record. This happens automatically—no manual tagging required.

  2. Log Context Propagation:

    • HTTP Requests: Spans created via Tracer->startSpan() (e.g., in controllers) propagate their context to logs.
    • Background Jobs: Use Tracer->extract() to inject context from messages (e.g., Laravel Queues, Symfony Messenger).
  3. Log Handler Integration: Ensure your Monolog handlers (e.g., monolog.handler.main) are configured to process records. Example:

    monolog:
        handlers:
            main:
                type: stream
                path: "%kernel.logs_dir%/%kernel.environment%.log"
                processors: [opentracing]  # Auto-added by the bundle
    

Common Use Cases

Scenario Implementation Pattern
API Request Tracing Start a span in the controller, log errors with context automatically included.
Queue Workers Extract span context from the message payload before processing.
Database Operations Wrap Doctrine queries in spans and log SQL with trace IDs.
Custom Services Inject TracerInterface and LoggerInterface into services to correlate logs/spans.

Integration Tips

  • Laravel: Use auxmoney/opentracing-bundle-core's Tracer facade in routes/services.
  • Doctrine: Extend Doctrine\DBAL\Connection to auto-start spans for queries.
  • Symfony Messenger: Pass span context via message metadata:
    $message->setMetadata(['opentracing_context' => $span->context()]);
    

Gotchas and Tips

Pitfalls

  1. Missing Core Bundle:

    • Error: Class 'Auxmoney\OpentracingBundle\TracerInterface' not found.
    • Fix: Install auxmoney/opentracing-bundle-core first.
  2. Context Not Propagating:

    • Cause: Spans not started before logging (e.g., logging in a service before the span exists).
    • Fix: Ensure spans are active in the call stack. Use Tracer->activeSpan() to check.
  3. Log Format Issues:

    • Symptom: opentracing-context appears as a string instead of JSON.
    • Fix: Verify Monolog’s json_formatter is enabled in handlers.
  4. Performance Overhead:

    • Tip: Disable the processor for non-critical logs (e.g., debug channel):
      monolog:
          handlers:
              debug:
                  processors: []  # Exclude opentracing
      

Debugging

  • Check Span Context:
    $span = \Auxmoney\OpentracingBundle\Tracer::activeSpan();
    dump($span->context()->toTraceId());  // Verify trace ID exists
    
  • Log Processor Order: The opentracing processor runs after other processors. Reorder in monolog.yaml if needed:
    processors: [datetime, memory_usage, opentracing]
    

Extension Points

  1. Custom Context Fields: Extend the processor to include additional span tags:

    // src/Logger/Processor/CustomOpenTracingProcessor.php
    class CustomOpenTracingProcessor extends OpenTracingProcessor
    {
        public function __invoke(array $record): array
        {
            $record = parent::__invoke($record);
            $record['custom_tag'] = $this->tracer->activeSpan()->getBaggageItem('custom.key');
            return $record;
        }
    }
    

    Register it in services.yaml:

    monolog.processor.opentracing: '@App\Logger\Processor\CustomOpenTracingProcessor'
    
  2. Conditional Logging: Skip context injection for sensitive logs:

    if (!$this->isSensitiveLog($record)) {
        $record = $this->opentracingProcessor->__invoke($record);
    }
    

Configuration Quirks

  • Symfony 6+: The bundle auto-registers via Flex. For manual setups, ensure bundles.php includes the bundle after MonologBundle.
  • PHP 8 Attributes: If using attributes for logging (e.g., [Log]), ensure the processor runs before attribute handlers.

Pro Tips

  • Correlate Logs with Traces: Use the UBER-TRACE-ID in your APM tool (e.g., Jaeger, Zipkin) to navigate logs within a trace.
  • Exclude Sensitive Data: Filter out PII from logs before the processor runs:
    $record['context']['password'] = '[REDACTED]';
    
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