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

inspector-apm/inspector-php

Inspector APM PHP agent: instrument your Laravel/PHP apps to collect traces, transactions, errors, and performance metrics. Lightweight integration, configurable sampling and context, helps you find slow requests and production issues fast.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require inspector-apm/inspector-php
    

    Add your INSPECTOR_API_KEY to .env:

    INSPECTOR_API_KEY=your_ingestion_key_here
    
  2. Basic Setup in Laravel: Add to bootstrap/app.php (or AppServiceProvider):

    use Inspector\Inspector;
    use Inspector\Configuration;
    
    $configuration = new Configuration(env('INSPECTOR_API_KEY'));
    $inspector = new Inspector($configuration);
    app()->singleton('inspector', fn() => $inspector);
    
  3. First Use Case: Instrument a route in app/Http/Controllers/ExampleController.php:

    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\App;
    
    public function index(Request $request) {
        $inspector = App::make('inspector');
        $inspector->startTransaction($request->path());
    
        $result = $inspector->addSegment(function($segment) {
            // Your business logic here
            return "Processed";
        }, 'process-data');
    
        return response()->json(['result' => $result]);
    }
    
  4. Verify: Check the Inspector Dashboard for traces.


Implementation Patterns

Core Workflows

1. Request-Level Tracing

  • Middleware Integration (Recommended for Laravel):
    // app/Http/Middleware/InspectorMiddleware.php
    public function handle(Request $request, Closure $next) {
        $inspector = app('inspector');
        $inspector->startTransaction($request->path());
        return $next($request);
    }
    
    Register in app/Http/Kernel.php:
    protected $middleware = [
        \App\Http\Middleware\InspectorMiddleware::class,
    ];
    

2. Business Logic Instrumentation

  • Service Layer:
    public function processOrder(Order $order) {
        $inspector = app('inspector');
        return $inspector->addSegment(function() use ($order) {
            // Order processing logic
            return $order->process();
        }, 'order-processing');
    }
    
  • Eloquent Models:
    public function scopeWithInspector($query) {
        $inspector = app('inspector');
        return $inspector->addSegment(function() use ($query) {
            return $query->get();
        }, 'eloquent-query');
    }
    

3. Queue Jobs

  • Job Wrapper:
    public function handle() {
        $inspector = app('inspector');
        $inspector->startTransaction('job:process-payment');
        // Job logic
    }
    

4. Database Queries

  • Auto-Instrumentation: Enabled by default for PDO/MySQLi.
  • Custom Spans for Complex Queries:
    $inspector->addSegment(function() {
        return DB::select('SELECT * FROM complex_query');
    }, 'complex-query');
    

5. Exceptions

  • Global Handler (Auto-captures unhandled exceptions):
    $inspector->registerGlobalHandler();
    
  • Manual Instrumentation:
    try {
        $result = $inspector->addSegment(...);
    } catch (\Exception $e) {
        $inspector->addSegment(function() use ($e) {
            throw $e; // Captures exception in trace
        }, 'failing-operation');
    }
    

Integration Tips

Laravel-Specific

  • Service Container Binding: Bind the inspector instance globally for easy access:

    $app->bind('inspector', function() {
        return new Inspector(new Configuration(env('INSPECTOR_API_KEY')));
    });
    
  • View Rendering: Track template rendering time:

    $inspector->addSegment(function() use ($view) {
        return $view->render();
    }, 'view-render');
    
  • API Resources: Instrument serialization:

    $inspector->addSegment(function() use ($resource) {
        return $resource->toArray();
    }, 'resource-serialization');
    

Performance Optimization

  • Sampling: Reduce overhead by sampling traces:
    $configuration->setSamplingRate(0.1); // 10% of requests
    
  • Exclude Paths: Skip low-value endpoints:
    $configuration->setExcludedPaths(['/health', '/ping']);
    

Advanced Patterns

  • Context Propagation: Pass context (e.g., user ID) across segments:

    $inspector->addSegment(function($segment) {
        $segment->setAttribute('user_id', auth()->id());
        // Logic
    }, 'user-specific-operation');
    
  • Custom Metrics: Track business metrics:

    $inspector->addMetric('orders_processed', 1, ['status' => 'success']);
    

Gotchas and Tips

Pitfalls

  1. Double Instrumentation:

    • Issue: Accidentally wrapping the same code in multiple segments.
    • Fix: Use unique segment names (e.g., user-service:fetch-profile).
  2. Segment Nesting Errors:

    • Issue: Segments not properly nested (e.g., ending a parent before child).
    • Fix: Use addSegment with closures to ensure proper scope:
      $result = $inspector->addSegment(function($segment) {
          $child = $segment->startChild('child-operation');
          $child->end();
          return "Done";
      }, 'parent-operation');
      
  3. Async Task Corruption:

    • Issue: Forked tasks (e.g., queues, fibers) corrupting segment hierarchy.
    • Fix: Always use fork() for concurrent tasks:
      $scope = $inspector->fork();
      $scope->startSegment('async-task')->end();
      
  4. Global Handler Conflicts:

    • Issue: registerGlobalHandler() overriding existing exception handlers.
    • Fix: Register it last or wrap in a try-catch:
      try {
          $inspector->registerGlobalHandler();
      } catch (\Exception $e) {
          // Handle conflict
      }
      
  5. High Cardinality Attributes:

    • Issue: Overloading Inspector with too many unique attributes (e.g., user IDs).
    • Fix: Use sampling or aggregate attributes:
      $segment->setAttribute('user_type', auth()->user()->type);
      

Debugging

  1. Missing Traces:

    • Check: Verify INSPECTOR_API_KEY is correct and the agent is running (if using agent mode).
    • Debug: Enable verbose logging:
      $configuration->setDebug(true);
      
  2. Performance Overhead:

    • Symptom: Slow responses after instrumentation.
    • Solution: Reduce segment granularity or increase sampling rate.
  3. Segment Not Showing:

    • Check: Ensure the segment is properly closed (use addSegment with closures).
    • Debug: Add a finally block to guarantee closure:
      $inspector->addSegment(function() {
          // Logic
      }, 'segment-name', function() {
          // Always runs
      });
      

Configuration Quirks

  1. Transport Layer:

    • Custom Transport: If using a proxy or air-gapped environment, ensure the transport class handles retries and batching:
      $inspector->setTransport(function() {
          return new CustomTransportWithRetry();
      });
      
  2. Environment Variables:

    • Fallback: Provide a default key for local development:
      $configuration = new Configuration(
          env('INSPECTOR_API_KEY', 'local-dev-key')
      );
      
  3. Sampling:

    • Dynamic Sampling: Adjust sampling based on request type:
      $configuration->setSamplingCallback(function($transaction) {
          return $transaction->getName() === '/api/payments' ? 1.0 : 0.1;
      });
      

Extension Points

  1. Custom Models:

    • Extend \Inspector\Models\Model to add domain-specific attributes:
      class CustomModel extends \Inspector\Models\Model {
          public function setCustomAttribute($key, $value) {
              $this->attributes[$key] = $value;
          }
      }
      
    • Register the custom model in the configuration:
      $configuration->setModelClass(CustomModel::class);
      
  2. Hooks:

    • Transaction Hooks: Add callbacks for transaction lifecycle:
      $inspector->onTransactionStart(function($transaction) {
          $transaction->setAttribute('environment', app()->environment());
      });
      
  3. Plugin System:

    • Laravel Service Provider: Create a provider to auto-register hooks:
      public function register() {
          $ins
      
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.
bugban/symfony
beyonder-capi/workflow-extensions-bundle
beyonder-capi/job-queue-bundle
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin