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

Elastic Apm Php Agent Laravel Package

nipwaayoni/elastic-apm-php-agent

Laravel-friendly Elastic APM PHP agent for instrumenting apps and sending performance data, errors, and transactions to an Elastic APM Server. Helps monitor response times, slow queries, and exceptions with simple setup and configurable reporting.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require nipwaayoni/elastic-apm-php-agent
    

    Require the autoloader in your Laravel app (handled automatically if using Composer).

  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="Nipwaayoni\ElasticApm\ElasticApmServiceProvider" --tag="config"
    

    Update .env with your Elastic APM server URL and service name:

    ELASTIC_APM_SERVER_URL=http://your-apm-server:8200
    ELASTIC_APM_SERVICE_NAME=your-laravel-app
    ELASTIC_APM_SECRET_TOKEN=your-secret-token  # Optional but recommended
    
  3. First Use Case Enable the agent in config/elastic-apm.php:

    'enabled' => env('APP_ENV') !== 'local',
    

    Test by triggering an error or logging a transaction:

    // In a route/controller
    \Nipwaayoni\ElasticApm\ElasticApm::transaction('test_transaction', function() {
        // Your code here
        throw new \Exception("Test error for APM");
    });
    

Implementation Patterns

Core Workflows

  1. Transaction Tracking Wrap critical paths (routes, jobs, commands) in transactions:

    // In routes/web.php
    Route::get('/critical-path', function() {
        ElasticApm::transaction('user_dashboard_load', function() {
            $user = User::with('orders')->find(1);
            return view('dashboard', compact('user'));
        });
    });
    
  2. Middleware Integration Auto-capture HTTP requests via middleware:

    namespace App\Http\Middleware;
    
    use Nipwaayoni\ElasticApm\ElasticApm;
    use Closure;
    
    class APMMiddleware
    {
        public function handle($request, Closure $next)
        {
            ElasticApm::transaction('http_request_' . $request->path(), function() use ($request, $next) {
                return $next($request);
            });
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $middleware = [
        // ...
        \App\Http\Middleware\APMMiddleware::class,
    ];
    
  3. Error Monitoring Capture exceptions globally:

    // In App\Exceptions\Handler
    public function report(Throwable $exception)
    {
        ElasticApm::captureException($exception);
        parent::report($exception);
    }
    
  4. Custom Spans Instrument database queries or external calls:

    ElasticApm::span('database_query', function() {
        DB::table('users')->where('id', 1)->get();
    });
    
  5. Queue Job Tracking Wrap jobs in transactions:

    namespace App\Jobs;
    
    use Nipwaayoni\ElasticApm\ElasticApm;
    use Illuminate\Bus\Queueable;
    
    class ProcessOrder implements Queueable
    {
        public function handle()
        {
            ElasticApm::transaction('process_order_job', function() {
                // Job logic
            });
        }
    }
    

Integration Tips

  • Laravel Debugbar: Use alongside barryvdh/laravel-debugbar for local debugging without APM noise.
  • Environment Awareness: Disable in local env to avoid overhead:
    'enabled' => app()->environment(['staging', 'production']),
    
  • Context Enrichment: Add custom context to transactions:
    ElasticApm::setContext(['user_id' => auth()->id(), 'request_id' => $request->header('X-Request-ID')]);
    
  • Queue Workers: Ensure workers are configured to include the APM agent:
    php artisan queue:work --queue=high --sleep=3 --tries=3 --daemon
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead

    • Issue: APM instrumentation adds latency (~5-10ms per transaction).
    • Fix: Disable in local env and avoid over-instrumenting. Use ignore_urls in config to exclude health checks or static assets:
      'ignore_urls' => [
          'health-check',
          'favicon.ico',
      ],
      
  2. Transaction Naming Collisions

    • Issue: Reusing the same transaction name (e.g., http_request_home) can obscure performance issues.
    • Fix: Use dynamic names with request paths or unique identifiers:
      ElasticApm::transaction('user_profile_' . $user->id, ...);
      
  3. Queue Job Visibility

    • Issue: Long-running jobs may not appear in APM if the transaction isn’t properly closed.
    • Fix: Use finally blocks or Laravel’s handle() with try-catch:
      public function handle()
      {
          try {
              ElasticApm::transaction('long_job', fn() => $this->process());
          } catch (\Throwable $e) {
              ElasticApm::captureException($e);
              throw $e;
          }
      }
      
  4. Database Query Spans

    • Issue: Spans for queries may not appear if the query is executed outside a transaction.
    • Fix: Wrap queries in spans explicitly:
      ElasticApm::span('fetch_user_orders', function() {
          return Order::where('user_id', 1)->get();
      });
      
  5. Configuration Caching

    • Issue: Changes to config/elastic-apm.php may not reflect without clearing config cache.
    • Fix: Run:
      php artisan config:clear
      
      Or restart your PHP process (e.g., php-fpm or queue:restart).

Debugging Tips

  1. Log Level Enable debug logging to troubleshoot:

    'log_level' => 'debug',
    

    Check logs at storage/logs/laravel.log.

  2. Agent Status Verify the agent is active:

    if (ElasticApm::isEnabled()) {
        // Agent is running
    }
    
  3. Network Issues

    • Symptom: Transactions disappear or time out.
    • Debug: Check APM server logs and ensure ELASTIC_APM_SERVER_URL is correct. Test connectivity:
      curl -v http://your-apm-server:8200
      
  4. Span Hierarchy

    • Issue: Spans not appearing as children of transactions.
    • Fix: Ensure spans are created within transactions:
      ElasticApm::transaction('parent', function() {
          ElasticApm::span('child', function() {
              // This span will be nested under 'parent'
          });
      });
      

Extension Points

  1. Custom Instrumentation Extend the agent by creating a facade wrapper:

    namespace App\Services;
    
    use Nipwaayoni\ElasticApm\ElasticApm as BaseApm;
    
    class APMService
    {
        public function trackApiCall(string $endpoint, callable $callback)
        {
            BaseApm::transaction("api_{$endpoint}", $callback);
        }
    }
    
  2. Event Listeners Hook into Laravel events to auto-instrument:

    // In EventServiceProvider
    protected $listen = [
        'Illuminate\Http\Kernel::terminate' => [
            \App\Listeners\InstrumentHttpRequest::class,
        ],
    ];
    
  3. Queue Failed Jobs Capture failed jobs with context:

    // In FailedJob class
    public function failed(Connection $connection, $exception)
    {
        ElasticApm::captureException($exception, [
            'job' => $this->job,
            'queue' => $this->queue,
        ]);
    }
    
  4. Custom Metrics Report custom metrics (e.g., cache hits/misses):

    ElasticApm::setCustomMetric('cache_hit_ratio', 0.95);
    
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.
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
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