PHP code example of overtrue / laravel-open-telemetry

1. Go to this page and download the library: Download overtrue/laravel-open-telemetry library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

overtrue / laravel-open-telemetry example snippets


// Old code (if you need scope activation)
$span = Measure::span('my-operation')->start(); // This now returns SpanInterface

// New code (for scope activation)
$startedSpan = Measure::span('my-operation')->startAndActivate(); // Returns StartedSpan

// config/otel.php
'enabled' => env('OTEL_ENABLED', true),

  'ignore_paths' => ['health*', 'telescope*', 'horizon*'],
  

  'allowed_headers' => ['x-request-id', 'user-agent', 'authorization'],
  

  'sensitive_headers' => ['authorization', 'cookie', 'x-api-key', '*-token'],
  

// config/otel.php
'watchers' => [
    \Overtrue\LaravelOpenTelemetry\Watchers\CacheWatcher::class => env('OTEL_CACHE_WATCHER_ENABLED', true),
    \Overtrue\LaravelOpenTelemetry\Watchers\QueryWatcher::class => env('OTEL_QUERY_WATCHER_ENABLED', true),
    // ...
],

use Overtrue\LaravelOpenTelemetry\Facades\Measure;

Measure::trace('process-user-data', function ($span) use ($user) {
    // Add attributes to the span
    $span->setAttribute('user.id', $user->id);

    // Your business logic here
    $this->process($user);

    // Add an event to mark a point in time within the span
    $span->addEvent('User processing finished');
});

// Create a span without activating its scope (safer for async operations)
$span = Measure::span('my-operation')
    ->setAttribute('operation.type', 'data-processing')
    ->setSpanKind(SpanKind::KIND_INTERNAL)
    ->start(); // Returns SpanInterface

// Your business logic here
$result = $this->processData();

// Remember to end the span manually
$span->end();

// Create a span and activate its scope (for nested operations)
$startedSpan = Measure::span('parent-operation')
    ->setAttribute('operation.type', 'user-workflow')
    ->setSpanKind(SpanKind::KIND_INTERNAL)
    ->startAndActivate(); // Returns StartedSpan

// Any spans created within this block will be children of this span
$childSpan = Measure::span('child-operation')->start();
$childSpan->end();

// The StartedSpan automatically manages scope cleanup
$startedSpan->end(); // Ends span and detaches scope

// Create a span and get both span and context for manual management
[$span, $context] = Measure::span('async-operation')
    ->setAttribute('operation.async', true)
    ->startWithContext(); // Returns [SpanInterface, ContextInterface]

// Use context for propagation (e.g., in HTTP headers)
$headers = Measure::propagationHeaders($context);

// Your async operation here
$span->end();

// Manually trace a block of database operations
$user = Measure::database('SELECT', 'users'); // Quick shortcut for database operations
// Or use the general trace method for more complex operations
$user = Measure::trace('repository:find-user', function ($span) use ($userId) {
    $span->setAttribute('db.statement', "SELECT * FROM users WHERE id = ?");
    $span->setAttribute('db.table', 'users');
    return User::find($userId);
});

// Quick shortcut for HTTP client requests
$response = Measure::httpClient('POST', 'https://api.example.com/users');
// Or use the general trace method for more control
$response = Measure::trace('api-call', function ($span) {
    $span->setAttribute('http.method', 'POST');
    $span->setAttribute('http.url', 'https://api.example.com/users');
    return Http::post('https://api.example.com/users', $data);
});

// For any custom operation, use the general trace method
$result = Measure::trace('process-payment', function ($span) use ($payment) {
    $span->setAttribute('payment.amount', $payment->amount);
    $span->setAttribute('payment.currency', $payment->currency);

    // Your business logic here
    return $this->processPayment($payment);
});

use Overtrue\LaravelOpenTelemetry\Facades\Measure;

$currentSpan = Measure::activeSpan();
$currentSpan->setAttribute('custom.attribute', 'some_value');

// In your routes/web.php or routes/api.php
Route::middleware('otel.traceid')->group(function () {
    Route::get('/api/users', [UserController::class, 'index']);
});

// app/Http/Kernel.php

// In the $middlewareGroups property for 'web' or 'api'
protected $middlewareGroups = [
    'web' => [
        // ...
        \Overtrue\LaravelOpenTelemetry\Http\Middleware\AddTraceId::class,
    ],
    // ...
];
bash
php artisan vendor:publish --provider="Overtrue\LaravelOpenTelemetry\OpenTelemetryServiceProvider" --tag=config