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

philkra/elastic-apm-php-agent

PHP agent for Elastic APM that instruments your application to capture transactions, spans, errors, and performance metrics. Sends telemetry to Elastic APM Server for tracing and monitoring, with support for web and CLI workloads and configurable sampling.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require philkra/elastic-apm-php-agent
    
  2. Configure via .env (Laravel):
    APM_SERVER_URL=http://localhost:8200
    APM_SERVICE_NAME=my-laravel-app
    APM_SERVICE_VERSION=1.0.0
    APM_ENVIRONMENT=production
    
  3. Initialize in bootstrap/app.php (Laravel 9+):
    $app->register(\PhilKra\ElasticApm\ElasticApmServiceProvider::class);
    
    Or manually in AppServiceProvider@boot():
    \PhilKra\ElasticApm\ElasticApm::initialize();
    

First Use Case: Auto-Captured HTTP Requests

  • No manual code changes needed for basic HTTP request tracing.
  • Verify transactions appear in Elastic APM UI under Service Map or Transactions.

Implementation Patterns

Framework Integration

Laravel Middleware for Context

// app/Http/Middleware/SetApmUserContext.php
public function handle($request, Closure $next)
{
    \PhilKra\ElasticApm\ElasticApm::setUserContext([
        'id' => auth()->id(),
        'email' => auth()->email(),
    ]);
    return $next($request);
}
  • Register middleware in app/Http/Kernel.php before other middleware.

Queue Job Instrumentation

use PhilKra\ElasticApm\ElasticApm;

// In your job's handle() method
$span = ElasticApm::startSpan('process_order');
try {
    // Business logic
} finally {
    $span->end();
}

Common Workflows

  1. Database Queries:

    $span = ElasticApm::startSpan('fetch_user_data');
    DB::table('users')->where('id', 1)->get();
    $span->end();
    
    • Use ElasticApm::startSpan() around Eloquent/Query Builder calls.
  2. HTTP Clients (Guzzle, HTTP Client):

    $span = ElasticApm::startSpan('call_external_api');
    Http::withOptions(['debug' => false])->get('https://api.example.com');
    $span->end();
    
  3. Custom Transactions:

    ElasticApm::startTransaction('custom_background_job');
    // Job logic
    ElasticApm::endTransaction();
    

Metadata Management

// Set global metadata (e.g., in AppServiceProvider)
ElasticApm::setMetadata([
    'labels' => ['team' => 'backend'],
    'environment' => config('app.env'),
]);

// Per-request metadata
ElasticApm::setTransactionName('api.v1.users.index');

Gotchas and Tips

Pitfalls

  1. Double Initialization:

    • Error: RuntimeException: APM agent already initialized.
    • Fix: Ensure ElasticApm::initialize() is called once (e.g., in AppServiceProvider@register()).
  2. Missing Transactions:

    • Cause: APM agent not auto-detecting Laravel’s request lifecycle.
    • Fix: Manually start/end transactions for CLI or non-web routes:
      ElasticApm::startTransaction('cli.command');
      // Command logic
      ElasticApm::endTransaction();
      
  3. Span Nesting:

    • Issue: Spans not appearing as children in traces.
    • Fix: Use ElasticApm::startSpan() with a parent span (if applicable):
      $parent = ElasticApm::getCurrentSpan();
      $child = ElasticApm::startSpan('child_task', $parent);
      
  4. Performance Overhead:

    • Tip: Disable in development:
      APM_ENVIRONMENT=development
      
    • Warning: Avoid excessive spans in hot paths (e.g., loops).

Debugging

  • Enable Debug Logging:
    APM_LOG_LEVEL=debug
    
  • Check Agent Status:
    if (!ElasticApm::isInitialized()) {
        // Handle error
    }
    
  • Validate Payloads: Use Elastic APM’s Service Map to verify transactions/spans are sent.

Extension Points

  1. Custom Error Handlers:

    ElasticApm::setErrorHandler(function (Throwable $e) {
        ElasticApm::captureException($e, [
            'custom_context' => ['user_id' => 123],
        ]);
    });
    
  2. Span Context Propagation: For distributed tracing, attach context to HTTP requests:

    $span = ElasticApm::startSpan('rpc_call');
    Http::withHeaders([
        'X-Elastic-Apm-Traceparent' => ElasticApm::getTraceparent(),
    ])->get('...');
    
  3. Async Processing:

    • Use ElasticApm::flush() to force-send data before app shutdown:
      register_shutdown_function(function() {
          ElasticApm::flush();
      });
      

Configuration Quirks

  • Server URL: Must start with http:// or https:// (no trailing slashes).
  • Service Name: Should match your Elastic APM service name (case-sensitive).
  • Environment: Must match Elastic APM’s configured environments (e.g., production, staging).
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