🎼 Laravel Integration Guide

Learn how to instrument your Laravel applications with TraceKit APM for zero-config distributed tracing and performance monitoring.

Zero-Config Automatic Tracing!

TraceKit Laravel package automatically traces HTTP requests, database queries, queue jobs, cache operations, and more with minimal setup. Just install and configure your API key!

📋

Prerequisites

  • • PHP 8.1 or higher
  • • Laravel 10.x, 11.x, or 12.x
  • • An active TraceKit account
  • • A generated API key from the API Keys page

🔍 What Gets Traced Automatically?

With TraceKit Laravel package installed, these operations are traced automatically with zero configuration:

ComponentWhat's CapturedAuto-Traced?
HTTP RequestsRoute, method, status, duration✓ Yes
Database QueriesSQL, bindings, duration, connection✓ Yes
Queue JobsJob class, queue name, status, payload✓ Yes
ExceptionsType, message, stack trace, context✓ Yes
Custom SpansManual instrumentation (optional)Manual

📦 Installation

Install the TraceKit Laravel package via Composer:

composer require tracekit/laravel-apm
🎉

Package Autodiscovery

The service provider is automatically registered via Laravel's package discovery. No need to manually register it!

⚙️ Configuration

1. Publish Configuration (Optional)

If you want to customize settings, publish the configuration file:

php artisan vendor:publish --provider="TraceKit\Laravel\TracekitServiceProvider"

This creates config/tracekit.php where you can customize settings.

2. Add API Key to .env

Add your TraceKit API key to your .env file:

# TraceKit APM Configuration
TRACEKIT_API_KEY=ctxio_your_generated_api_key_here
TRACEKIT_ENDPOINT=https://app.tracekit.dev/v1/traces
TRACEKIT_SERVICE_NAME=my-laravel-app
TRACEKIT_ENABLED=true
⚠️

Important Security Note

Never commit your API key to version control. Keep it in your .env file and use environment-specific values.

🚀 Laravel 12+ Middleware Setup

For Laravel 12+, middleware registration has changed. The package attempts automatic registration, but if needed, manually add the middleware to bootstrap/app.php:

<?php

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();
💡

Laravel 10 & 11

For Laravel 10 and 11, the middleware is registered automatically via the service provider. No manual configuration needed!

Configuration Options

Available configuration options in config/tracekit.php:

<?php

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),
        'queue' => env('TRACEKIT_QUEUE_ENABLED', true),
        'redis' => env('TRACEKIT_REDIS_ENABLED', true),
    ],

    // 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
    'include_query_bindings' => env('TRACEKIT_INCLUDE_BINDINGS', true),
];

🔧 Manual Instrumentation (Optional)

For custom business logic or specific operations you want to measure, you can manually create spans:

<?php

use TraceKit\Laravel\TracekitClient;

class OrderController extends Controller
{
    public function processOrder(Request $request, TracekitClient $tracekit)
    {
        // Create a custom span
        $span = $tracekit->startSpan('process-order', null, [
            'order.id' => $request->input('order_id'),
            'user.id' => auth()->id(),
        ]);

        try {
            $order = $this->createOrder($request->all());
            $this->processPayment($order);
            $this->sendConfirmation($order);

            $tracekit->endSpan($span, [
                'order.total' => $order->total,
                'order.items_count' => $order->items()->count(),
            ]);

            return response()->json($order, 201);
        } catch (\Exception $e) {
            $tracekit->recordException($span, $e);
            $tracekit->endSpan($span, [], 'ERROR');
            throw $e;
        }
    }
}

Complete Example

Here's a complete example showing automatic and manual tracing:

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use TraceKit\Laravel\TracekitClient;

class UserController extends Controller
{
    // HTTP requests are automatically traced!
    public function index()
    {
        // Database queries are automatically traced!
        $users = User::where('active', true)->get();

        return response()->json($users);
    }

    // You can add custom spans for specific operations
    public function processUserData(Request $request, TracekitClient $tracekit)
    {
        // Start custom span
        $span = $tracekit->startSpan('process-user-data', null, [
            'user.count' => $request->input('user_ids')->count(),
        ]);

        try {
            // Your business logic here
            $results = [];
            foreach ($request->input('user_ids') as $userId) {
                $user = User::find($userId);
                $results[] = $this->processUser($user);
            }

            $tracekit->endSpan($span, [
                'results.count' => count($results),
            ]);

            return response()->json($results);
        } catch (\Exception $e) {
            $tracekit->recordException($span, $e);
            $tracekit->endSpan($span, [], 'ERROR');
            throw $e;
        }
    }

    private function processUser($user)
    {
        // Database queries here are also automatically traced!
        $user->last_processed_at = now();
        $user->save();

        return $user;
    }
}
🎉

You're all set!

Your Laravel application is now sending traces to TraceKit. Visit the Dashboard to see your traces.

🔧 Troubleshooting

Traces Not Appearing?

  1. Verify your API key is correct in .env
  2. Check TRACEKIT_ENABLED=true in your .env
  3. Clear config cache: php artisan config:clear
  4. Check Laravel logs in storage/logs/laravel.log
  5. Verify TraceKit endpoint is accessible

Package Not Auto-Discovered?

Run package discovery manually:

php artisan package:discover php artisan config:clear

🚀 Next Steps

  • Explore your traces on the Traces page to identify slow queries and performance bottlenecks
  • Configure alert rules to get notified when issues occur
  • Add custom spans for specific business logic you want to measure
  • Adjust sampling rates for high-traffic applications
💡

Pro Tip

Enable query bindings to see actual SQL values in traces. Just set TRACEKIT_INCLUDE_BINDINGS=true in your .env file. Perfect for debugging!