PHP code example of tracekit / laravel-apm

1. Go to this page and download the library: Download tracekit/laravel-apm 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/ */

    

tracekit / laravel-apm example snippets


use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;
use TraceKit\Laravel\Middleware\TracekitMiddleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->web(append: [
            TracekitMiddleware::class,
        ]);
        $middleware->api(append: [
            TracekitMiddleware::class,
        ]);
    })
    // ... rest of your configuration
    ->create();

return [
    // Enable/disable tracing
    'enabled' => env('TRACEKIT_ENABLED', env('APP_ENV') !== 'local'),

    // Your TraceKit API key
    'api_key' => env('TRACEKIT_API_KEY', ''),

    // OTLP endpoint for sending traces
    'endpoint' => env('TRACEKIT_ENDPOINT', 'https://app.tracekit.dev/v1/traces'),

    // Service name as it appears in TraceKit
    'service_name' => env('TRACEKIT_SERVICE_NAME', env('APP_NAME', 'laravel-app')),

    // Sample rate (0.0 to 1.0)
    'sample_rate' => env('TRACEKIT_SAMPLE_RATE', 1.0),

    // Enable/disable specific features
    'features' => [
        'http' => env('TRACEKIT_HTTP_ENABLED', true),
        'database' => env('TRACEKIT_DATABASE_ENABLED', true),
        'cache' => env('TRACEKIT_CACHE_ENABLED', true),      // Coming soon
        'queue' => env('TRACEKIT_QUEUE_ENABLED', true),
        'redis' => env('TRACEKIT_REDIS_ENABLED', true),      // Coming soon
    ],

    // Routes to ignore
    'ignored_routes' => [
        '/health',
        '/up',
        '/_healthz',
    ],

    // Slow query threshold (ms)
    'slow_query_threshold' => env('TRACEKIT_SLOW_QUERY_MS', 100),

    // Include query bindings in traces
    '



namespace App\Http\Controllers;

use Illuminate\Http\Request;

class CheckoutController extends Controller
{
    public function processPayment(Request $request)
    {
        $cart = $request->input('cart');
        $userId = $request->input('user_id');

        // Automatic snapshot capture with label
        tracekit_snapshot('checkout-validation', [
            'user_id' => $userId,
            'cart_items' => count($cart['items'] ?? []),
            'total_amount' => $cart['total'] ?? 0,
        ]);

        try {
            // Process payment
            $result = $this->paymentService->charge($cart['total'], $userId);

            // Another checkpoint
            tracekit_snapshot('payment-success', [
                'user_id' => $userId,
                'payment_id' => $result['payment_id'],
                'amount' => $result['amount'],
            ]);

            return response()->json(['success' => true]);

        } catch (\Exception $e) {
            // Automatic error capture (configured in service provider)
            tracekit_error_snapshot($e, [
                'user_id' => $userId,
                'cart_total' => $cart['total'] ?? 0,
            ]);

            return response()->json(['error' => 'Payment failed'], 500);
        }
    }
}

// Basic snapshot capture
tracekit_snapshot('my-label', ['key' => 'value']);

// Debug helper (logs + captures)
tracekit_debug('debug-point', ['data' => $data]);

// Error snapshot with exception details
tracekit_error_snapshot($exception, ['context' => 'additional data']);

// Exceptions are automatically captured - just throw them as normal!
Route::post('/payment', function (Request $request) {
    if (!$request->has('amount')) {
        // This exception will be automatically captured with full context
        throw new \Exception('Amount is eate($request->all());
    } catch (\Exception $e) {
        // Optional: Add additional context before exception is auto-captured
        tracekit_snapshot('checkout-failed', [
            'cart_total' => $request->input('total'),
            'user_id' => auth()->id(),
            'error' => $e->getMessage(),
        ]);
        
        throw $e; // Still automatically captured!
    }
});

tracekit_snapshot('user-login', [
    'username' => 'jdoe',              // Sent as-is
    'password' => 'secret123',          // -> [REDACTED:sensitive_name]
    'api_key' => 'sk_live_abc...',      // -> [REDACTED:sensitive_name]
    'email' => '[email protected]',      // -> [REDACTED:email]
    'card' => '4111111111111111',       // -> [REDACTED:credit_card]
]);

// No code changes needed — the SDK handles this automatically.
// Kill switch state is cached and refreshed on each poll cycle.

// To check kill switch state manually:
$client = app(\TraceKit\Laravel\SnapshotClient::class);
// The client checks cache for kill switch state before every capture

// No configuration needed — circuit breaker is built into the SnapshotClient.
// When tripped, you'll see a log message:
// "[TraceKit] Circuit breaker open — pausing code monitoring for 5 minutes"

use TraceKit\Laravel\Facades\Tracekit;

// Initialize metrics (typically in a service provider or route file)
$requestCounter = Tracekit::counter('http.requests.total', ['service' => 'my-app']);
$activeRequestsGauge = Tracekit::gauge('http.requests.active', ['service' => 'my-app']);
$durationHistogram = Tracekit::histogram('http.request.duration', ['unit' => 'ms']);

// Use metrics in your routes or controllers
$requestCounter->inc();  // Increment by 1
$activeRequestsGauge->set(42);  // Set to specific value
$durationHistogram->record(125.5);  // Record observation

$requestCounter = Tracekit::counter('http.requests.total', [
    'service' => 'my-app',
    'environment' => config('app.env')
]);

$requestCounter->inc();  // Increment by 1
$requestCounter->add(5);  // Add specific amount

$activeUsersGauge = Tracekit::gauge('users.active', ['service' => 'my-app']);

$activeUsersGauge->set(150);  // Set to specific value
$activeUsersGauge->inc();  // Increment by 1
$activeUsersGauge->dec();  // Decrement by 1

$durationHistogram = Tracekit::histogram('http.request.duration', ['unit' => 'ms']);

$startTime = microtime(true);
// ... do work ...
$duration = (microtime(true) - $startTime) * 1000;
$durationHistogram->record($duration);

use TraceKit\Laravel\Facades\Tracekit;

// Initialize metrics once (e.g., in routes/web.php or a service provider)
$requestCounter = Tracekit::counter('http.requests.total', ['service' => 'my-app']);
$activeRequestsGauge = Tracekit::gauge('http.requests.active', ['service' => 'my-app']);
$durationHistogram = Tracekit::histogram('http.request.duration', ['unit' => 'ms']);
$errorCounter = Tracekit::counter('http.errors.total', ['service' => 'my-app']);

Route::get('/api/users', function () use ($requestCounter, $activeRequestsGauge, $durationHistogram) {
    $startTime = microtime(true);
    $activeRequestsGauge->inc();

    try {
        $users = User::all();
        return response()->json($users);
    } finally {
        $requestCounter->inc();
        $activeRequestsGauge->dec();
        $duration = (microtime(true) - $startTime) * 1000;
        $durationHistogram->record($duration);
    }
});



namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use TraceKit\Laravel\Facades\Tracekit;

class MetricsMiddleware
{
    private $requestCounter;
    private $activeRequestsGauge;
    private $durationHistogram;
    private $errorCounter;

    public function __construct()
    {
        $this->requestCounter = Tracekit::counter('http.requests.total', ['service' => config('app.name')]);
        $this->activeRequestsGauge = Tracekit::gauge('http.requests.active', ['service' => config('app.name')]);
        $this->durationHistogram = Tracekit::histogram('http.request.duration', ['unit' => 'ms']);
        $this->errorCounter = Tracekit::counter('http.errors.total', ['service' => config('app.name')]);
    }

    public function handle(Request $request, Closure $next)
    {
        $startTime = microtime(true);
        $this->activeRequestsGauge->inc();

        $response = $next($request);

        $this->requestCounter->inc();
        $this->activeRequestsGauge->dec();
        $duration = (microtime(true) - $startTime) * 1000;
        $this->durationHistogram->record($duration);

        if ($response->status() >= 400) {
            $this->errorCounter->inc();
        }

        return $response;
    }
}

// Track requests by endpoint
$requestCounter = Tracekit::counter('http.requests.total', [
    'service' => 'my-app',
    'endpoint' => '/api/users',
    'method' => 'GET'
]);

// Track cache hits/misses
$cacheHitCounter = Tracekit::counter('cache.hits', [
    'service' => 'my-app',
    'cache_type' => 'redis'
]);

$queryCounter = Tracekit::counter('db.queries.total', ['database' => 'mysql']);
$queryDuration = Tracekit::histogram('db.query.duration', ['unit' => 'ms']);

DB::listen(function ($query) use ($queryCounter, $queryDuration) {
    $queryCounter->inc();
    $queryDuration->record($query->time);
});

$jobCounter = Tracekit::counter('queue.jobs.total', ['queue' => 'default']);
$jobDuration = Tracekit::histogram('queue.job.duration', ['unit' => 'ms']);

// In your job class
public function handle()
{
    $startTime = microtime(true);

    // ... job logic ...

    $duration = (microtime(true) - $startTime) * 1000;
    $jobDuration->record($duration);
    $jobCounter->inc();
}

$ordersCounter = Tracekit::counter('orders.created', ['service' => 'my-app']);
$revenueGauge = Tracekit::gauge('revenue.total', ['currency' => 'USD']);

// Track business events
$ordersCounter->inc();
$revenueGauge->set($totalRevenue);

use Illuminate\Support\Facades\Http;

// All of these automatically create CLIENT spans:
Http::get('http://payment-service/charge');
Http::post('http://inventory-service/reserve', ['item_id' => 123]);
Http::withToken($token)->get('http://user-service/profile/123');

return [
    // ... other config

    // Map localhost URLs to actual service names
    'service_name_mappings' => [
        'localhost:8082' => 'payment-service',
        'localhost:8083' => 'user-service',
        'localhost:8084' => 'inventory-service',
        'localhost:5001' => 'analytics-service',
    ],
];

use Illuminate\Support\Facades\Http;

// Now requests to localhost:8082 will show as "payment-service" in the service graph
$response = Http::get('http://localhost:8082/charge');
// -> Creates CLIENT span with peer.service = "payment-service"

use Illuminate\Support\Facades\Http;

Route::post('/checkout', function (Request $request) {
    // This HTTP call automatically creates a CLIENT span
    $paymentResponse = Http::post('http://payment-service/charge', [
        'amount' => $request->input('amount'),
        'user_id' => auth()->id(),
    ]);

    // This one too!
    $inventoryResponse = Http::post('http://inventory-service/reserve', [
        'item_id' => $request->input('item_id'),
    ]);

    return response()->json([
        'status' => 'success',
        'payment_id' => $paymentResponse['payment_id'],
    ]);
});

return [
    'auto_instrument_http_client' => env('TRACEKIT_AUTO_INSTRUMENT_HTTP_CLIENT', true),
];

use TraceKit\Laravel\TracekitClient;

class MyController extends Controller
{
    public function myMethod(TracekitClient $tracekit)
    {
        $span = $tracekit->startSpan('my-custom-operation', null, [
            'user.id' => auth()->id(),
            'custom.attribute' => 'value',
        ]);

        try {
            // Your code here
            $result = $this->doSomething();

            $tracekit->endSpan($span, [
                'result.count' => count($result),
            ]);
        } catch (\Exception $e) {
            $tracekit->recordException($span, $e);
            $tracekit->endSpan($span, [], 'ERROR');
            throw $e;
        }
    }
}
bash
php artisan tracekit:install
bash
php artisan serve
bash
php artisan vendor:publish --tag=tracekit-config