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

Inspector Symfony Laravel Package

arnedesmedt/inspector-symfony

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require inspector-apm/inspector-symfony
    
  2. Configure the Ingestion Key Create config/packages/inspector.yaml:

    inspector:
        ingestion_key: "YOUR_INSPECTOR_INGESTION_KEY"
    

    (Obtain the key from your Inspector dashboard.)

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

    return [
        // ...
        Inspector\InspectorSymfonyBundle::class => ['all' => true],
    ];
    
  4. Verify Integration Run a request and check the Inspector UI for traces.


First Use Case: Debugging Slow Endpoints

  • Trigger a Trace: Visit a slow API endpoint or simulate a delay in a controller.
  • Analyze in Inspector: Inspect the generated trace to identify bottlenecks (e.g., database queries, external API calls).
  • Filter by Environment: Use APP_ENV=prod or APP_ENV=dev to isolate issues.

Implementation Patterns

Core Workflows

  1. Automatic Instrumentation

    • The bundle auto-instruments Symfony’s HTTP kernel, events, and services.
    • No manual code changes are needed for basic tracing (e.g., controllers, commands).
  2. Manual Instrumentation (Advanced) Use the Inspector\Inspector service to manually start/stop spans:

    use Inspector\Inspector;
    
    public function someAction(Inspector $inspector)
    {
        $span = $inspector->startSpan('custom_operation');
        try {
            // Business logic
        } finally {
            $span->finish();
        }
    }
    
  3. Event-Based Tracing Attach spans to Symfony events (e.g., Kernel::CONTROLLER):

    # config/services.yaml
    services:
        App\EventListener\InspectorListener:
            tags:
                - { name: 'kernel.event_listener', event: 'kernel.controller', method: 'onKernelController }
    
    public function onKernelController(GetResponseForControllerEvent $event, Inspector $inspector)
    {
        $span = $inspector->startSpan('pre_controller_logic');
        // ...
    }
    
  4. Database Query Tracing Integrate with Doctrine listeners (if using doctrine/doctrine-bundle):

    use Inspector\Inspector;
    use Doctrine\DBAL\Event\Listeners\SQLLogger;
    
    public function __construct(Inspector $inspector)
    {
        $this->inspector = $inspector;
    }
    
    public function postConnect(ConnectionEventArgs $args)
    {
        $logger = new SQLLogger($this->inspector);
        $args->getConnection()->getConfiguration()->setSQLLogger($logger);
    }
    

Integration Tips

  • Environment-Specific Keys: Use %env(INSPECTOR_KEY)% in inspector.yaml for security.
  • Sampling: Configure sampling rules in inspector.yaml:
    inspector:
        ingestion_key: "YOUR_KEY"
        sampling:
            rate: 0.1  # Sample 10% of requests
    
  • Custom Attributes: Add context to spans:
    $span->setAttribute('user_id', $user->getId());
    $span->setAttribute('custom_metric', 42);
    
  • Error Tracking: Automatically capture exceptions:
    try {
        // Risky code
    } catch (\Exception $e) {
        $span->recordException($e);
        throw $e;
    }
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead

    • Issue: Heavy instrumentation may slow production requests.
    • Fix: Use sampling (sampling.rate) or disable in production temporarily:
      inspector:
          enabled: "%kernel.debug%"  # Only trace in dev
      
  2. Sensitive Data Leaks

    • Issue: Accidental logging of passwords/tokens in spans.
    • Fix: Redact data before setting attributes:
      $span->setAttribute('user_email', strtok($user->getEmail(), '@'));
      
  3. Doctrine Integration Conflicts

    • Issue: SQLLogger may conflict with existing Doctrine profilers.
    • Fix: Disable other profilers or use Inspector\Doctrine\SQLLogger explicitly.
  4. Missing Traces in CLI

    • Issue: Commands (e.g., php bin/console) may not appear in Inspector.
    • Fix: Manually start a root span in your command:
      public function handle()
      {
          $inspector = $this->getInspector();
          $span = $inspector->startSpan('cli_command');
          // Command logic
          $span->finish();
      }
      

Debugging Tips

  • Check Bundle Status Verify the bundle is loaded:

    php bin/console debug:container inspector
    

    Should return Inspector\InspectorSymfonyBundle.

  • Enable Debug Logging Add to config/packages/dev/inspector.yaml:

    inspector:
        debug: true
    

    Check logs for initialization errors.

  • Validate Ingestion Key Test with a dummy key first to rule out auth issues:

    inspector:
        ingestion_key: "test_123"
    

    (No data will be sent, but errors will surface.)

  • Network Issues If traces don’t appear, check:

    • Inspector’s status page.
    • Firewall/proxy blocking ingest.inspector.dev.

Extension Points

  1. Custom Span Processors Extend Inspector\SpanProcessorInterface to modify spans before sending:

    class CustomSpanProcessor implements SpanProcessorInterface
    {
        public function process(Span $span, Context $context): void
        {
            $span->setAttribute('custom_tag', 'value');
        }
    }
    

    Register in services.yaml:

    services:
        App\SpanProcessor\CustomSpanProcessor:
            tags: ['inspector.span_processor']
    
  2. Override Default Instrumentation Disable auto-instrumentation and implement your own:

    inspector:
        auto_instrument: false
    

    Then manually instrument critical paths (e.g., via event listeners).

  3. Custom Metrics Use Inspector\Metrics to track business metrics:

    $metrics->increment('orders.processed');
    $metrics->set('inventory.level', 100);
    
  4. Async Processing For long-running tasks (e.g., queues), use background spans:

    $span = $inspector->startSpan('async_task', ['async' => true]);
    // Dispatch to a queue worker
    
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.
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
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver