DIGITAL4FRONT / CODE BASE

Laravel 8 Structured JSON Logs and Correlation IDs

Implement structured JSON diagnostic logs and searchable MySQL business audit records in Laravel 8.75, linked by a UUID across API requests, error responses, queue jobs and trusted outbound HTTP calls—without new Composer packages.

Share

For a Laravel 8 API, use **two connected records rather than one oversized log table**: structured diagnostic events in rotating JSON files, and concise business audit events in MySQL. Assign one correlation UUID to each incoming API request and carry it into both records. Propagate that UUID explicitly into queued jobs and trusted outbound HTTP calls. This makes troubleshooting practical without storing entire request bodies, headers, server arrays or stack traces in every database row.

The implementation below targets Laravel 8.75 and PHP 7.3/8.0. It uses Laravel's existing Monolog integration and does not require new Composer packages. It also works as a migration starting point for a later Laravel upgrade.

Should Laravel logs live in files or MySQL?

Diagnostic and business audit records have different purposes. A diagnostic entry tells an operator that an API call timed out or a worker failed. An audit record tells the business which authenticated user changed a payment or approved a sale.

Writing every request body and stack trace directly to MySQL increases table size, database write traffic, backup size and privacy exposure. File logs are simpler for short-lived diagnostics and are easy to ship to a central log service later. Conversely, a database is useful for querying audit events alongside users, sales or transactions and enforcing relationships and access rules.

A split approach is a sensible default for this POS-style backend, but there are trade-offs. File logs need rotation, backup or central collection, and secure access; a multi-server deployment cannot reliably search one local file. MySQL audit records need indexing, capacity planning, access controls and a defined retention policy. Neither storage option should be treated as automatically permanent or secure.

Use the same `correlation_id` value in the JSON diagnostic record and the audit table's existing `reference` field, provided that field can store a 36-character UUID.

1. Configure a JSON diagnostic channel

Laravel 8 already uses Monolog. Add a `diagnostic` channel inside the existing `channels` array in `config/logging.php`:

php
'diagnostic' => [
    'driver' => 'daily',
    'path' => storage_path('logs/diagnostic.jsonl'),
    'level' => env('LOG_LEVEL', 'info'),
    'days' => 14,
    'locking' => true,
    'tap' => [App\Logging\JsonCorrelationFormatter::class],
],

Set `LOG_CHANNEL=diagnostic` in the deployment environment if framework exceptions and ordinary `Log::info()` calls should go to this channel. Retain any additional channels your application genuinely needs. Make sure `storage/logs` is writable and unavailable to web visitors.

Create `app/Logging/JsonCorrelationFormatter.php`:

php
<?php
namespace App\Logging;

use App\Support\CorrelationContext;
use Monolog\Formatter\JsonFormatter;

class JsonCorrelationFormatter
{
    public function __invoke($logger)
    {
        $monolog = $logger->getLogger();

        foreach ($monolog->getHandlers() as $handler) {
            $handler->setFormatter(new JsonFormatter(
                JsonFormatter::BATCH_MODE_JSON,
                true
            ));
        }

        // Laravel 8 normally uses Monolog 2, whose processors
        // receive and return an associative record array.
        $monolog->pushProcessor(function (array $record): array {
            $id = app(CorrelationContext::class)->current();

            if ($id !== null) {
                $record['context']['correlation_id'] = $id;
            }

            return $record;
        });
    }
}

`JsonFormatter` writes a JSON object followed by a newline. The processor adds the active correlation ID automatically, including to normal Laravel log calls and most framework exception reports written while that context is active. It intentionally does not add request bodies or headers. This processor signature is for Monolog 2; review it when upgrading to an application that uses Monolog 3.

2. Keep correlation context safe for both requests and workers

Long-running workers process many jobs in the same PHP process. A global variable or logger context that is not reset can accidentally attach one customer's request ID to the next job.

Create `app/Support/CorrelationContext.php`:

php
<?php
namespace App\Support;

final class CorrelationContext
{
    private $stack = [];

    public function push(string $id): void
    {
        $this->stack[] = $id;
    }

    public function current(): ?string
    {
        if (count($this->stack) === 0) {
            return null;
        }

        return $this->stack[count($this->stack) - 1];
    }

    public function pop(): void
    {
        array_pop($this->stack);
    }
}

In the existing `register()` method of `app/Providers/AppServiceProvider.php`, register a singleton:

php
$this->app->singleton(
    \App\Support\CorrelationContext::class,
    function () {
        return new \App\Support\CorrelationContext();
    }
);

A stack allows a synchronously executed job to use the same ID and then restore its parent request context. The `finally` blocks used below prevent IDs from leaking into the next request or queue job. This design assumes Laravel's usual sequential PHP request/worker model; adapt it for coroutine or concurrently multiplexed runtimes.

3. Generate one UUID per API request

Create `app/Http/Middleware/AssignCorrelationId.php`:

php
<?php
namespace App\Http\Middleware;

use App\Support\CorrelationContext;
use Closure;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class AssignCorrelationId
{
    public function handle($request, Closure $next)
    {
        // Generate a new server-controlled ID for each request.
        $id = (string) Str::uuid();
        $context = app(CorrelationContext::class);

        $request->attributes->set('correlation_id', $id);
        $context->push($id);

        try {
            Log::info('api.request.received', [
                'method' => $request->method(),
            ]);

            $response = $next($request);
            $response->headers->set('X-Correlation-ID', $id);

            return $response;
        } finally {
            $context->pop();
        }
    }
}

Register this middleware near the beginning of the `api` middleware group in `app/Http/Kernel.php`:

php
'api' => [
    \App\Http\Middleware\AssignCorrelationId::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],

Merge it with the application's **existing** `api` group rather than deleting other middleware. Place the correlation middleware early enough to cover the operations you need. This example generates a fresh ID instead of trusting a caller-supplied one; if requests arrive through a trusted proxy, validate and define an explicit upstream-header policy first.

A client can now include the returned `X-Correlation-ID` header in a support ticket. Do not use a single ID for an entire user session: correlation here is per API request.

4. Cover exceptions and error responses

There is a subtle Laravel 8 issue: if an exception propagates beyond middleware, its `finally` block clears the active context before Laravel's outer exception handler reports the error. A generic claim that middleware alone correlates **every** exception would therefore be incorrect.

In `app/Exceptions/Handler.php`, extend the existing handler with these methods; add `use Throwable;` if needed:

php
protected function context()
{
    $details = parent::context();

    if (app()->bound('request')) {
        $id = request()->attributes->get('correlation_id');

        if (is_string($id)) {
            $details['correlation_id'] = $id;
        }
    }

    return $details;
}

public function render($request, Throwable $exception)
{
    $response = parent::render($request, $exception);
    $id = $request->attributes->get('correlation_id');

    if (is_string($id)) {
        $response->headers->set('X-Correlation-ID', $id);
    }

    return $response;
}

This adds the ID to Laravel's exception context and the rendered error response, even when the middleware has unwound. Errors occurring before the correlation middleware runs may not have an ID. Exceptions handled and reported by other custom mechanisms must be checked separately.

5. Store business audit events in MySQL

Business audit events should contain a small, deliberate schema: the action, actor, affected record, outcome and correlation reference. Do not store all headers, complete payment requests, credentials or full stack traces in the audit table.

A new installation could create the following table through a Laravel migration. If your existing audit table has a `reference` column, migrate that schema carefully rather than creating a duplicate audit system:

php
Schema::create('audit_events', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->uuid('reference')->index();
    $table->unsignedBigInteger('actor_id')->nullable()->index();
    $table->string('event', 80);
    $table->string('subject_type', 80);
    $table->unsignedBigInteger('subject_id');
    $table->boolean('success');
    $table->timestamps();
});

Import `Illuminate\Database\Schema\Blueprint` and `Illuminate\Support\Facades\Schema` in the migration. An audit insert belongs inside the same `DB::transaction()` as the successful business change when they must commit or roll back together:

php
use App\Support\CorrelationContext;
use Illuminate\Support\Facades\DB;

$id = app(CorrelationContext::class)->current();

if ($id === null) {
    throw new RuntimeException('Missing correlation context.');
}

DB::transaction(function () use ($id, $orderId) {
    // Execute the authorised business update in this transaction.

    DB::table('audit_events')->insert([
        'reference' => $id,
        'actor_id' => auth()->id(),
        'event' => 'order.approved',
        'subject_type' => 'order',
        'subject_id' => $orderId,
        'success' => true,
        'created_at' => now(),
        'updated_at' => now(),
    ]);
});

The business update is deliberately a placeholder because every POS application has different tables and authorisation rules. An audit row should only claim that an order was approved after the actual approval operation succeeds. Failed attempts that must be retained need their own controlled, post-rollback audit write; don't lose them inside a rolled-back transaction.

6. Carry the ID into queued Laravel jobs

Laravel 8 does not provide the newer `Log::shareContext()` interface. It does have `Log::withContext()`, but context applied to one logger does not automatically follow a separately executed queued job. Serialize the ID as an explicit job property and restore it while the job runs.

Create `app/Jobs/Middleware/ApplyCorrelationId.php`:

php
<?php
namespace App\Jobs\Middleware;

use App\Support\CorrelationContext;

class ApplyCorrelationId
{
    public function handle($job, $next)
    {
        $context = app(CorrelationContext::class);
        $context->push($job->correlationId);

        try {
            return $next($job);
        } finally {
            $context->pop();
        }
    }
}

Here is a complete illustrative job using that middleware (`app/Jobs/RecordPaymentStatus.php`):

php
<?php
namespace App\Jobs;

use App\Jobs\Middleware\ApplyCorrelationId;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class RecordPaymentStatus implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $paymentId;
    public $correlationId;

    public function __construct(int $paymentId, string $correlationId)
    {
        $this->paymentId = $paymentId;
        $this->correlationId = $correlationId;
    }

    public function middleware()
    {
        return [new ApplyCorrelationId()];
    }

    public function handle()
    {
        Log::info('payment.job.started', [
            'payment_id' => $this->paymentId,
        ]);

        // Perform validated, idempotent business work here.
    }
}

From an authenticated request handler already covered by the middleware, dispatch with the same ID:

php
$id = app(\App\Support\CorrelationContext::class)->current();
\App\Jobs\RecordPaymentStatus::dispatch($paymentId, $id);

Validate that `$id` is present before dispatching outside an HTTP context. With `QUEUE_CONNECTION=sync`, the job executes in the current request; with a real asynchronous queue it executes in a separate worker. The explicit property works for both. If jobs dispatch other jobs, pass the same ID again rather than assuming context is automatically serialised.

7. Propagate the ID to a trusted outbound payment API

Use Laravel 8's built-in HTTP client to attach the correlation header to a known, trusted destination:

php
use App\Support\CorrelationContext;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

$id = app(CorrelationContext::class)->current();

if ($id === null) {
    throw new RuntimeException('Missing correlation context.');
}

$response = Http::withHeaders([
    'X-Correlation-ID' => $id,
])->timeout(10)->post(config('services.payment.endpoint'), [
    'payment_reference' => $paymentReference,
]);

Log::info('payment.api.response', [
    'operation' => 'payment-status',
    'status' => $response->status(),
]);

Configure `services.payment.endpoint` with your actual trusted endpoint, and use the payment API's documented payload and authentication. This snippet illustrates correlation propagation, not a universal payment API integration. Never send internal IDs to arbitrary user-controlled URLs. Log only an approved operation name and status; avoid raw tokens, customer data, request bodies and entire response payloads.

8. Search, performance, security and retention

In JSON logs, the correlation ID appears under `context.correlation_id`. A diagnostic event might look like this (illustrative values):

json
{"message":"payment.api.response","context":{"operation":"payment-status","status":200,"correlation_id":"07e0f92d-f586-4410-a01e-6d4c6e48935e"}}

Find the ID in the relevant rotated log files using a controlled server-side search, or use a centralised log index as the system grows. Query the database audit table by its indexed reference:

sql
SELECT event, actor_id, subject_type, subject_id, success, created_at
FROM audit_events
WHERE reference = '07e0f92d-f586-4410-a01e-6d4c6e48935e'
ORDER BY created_at;

File writes avoid doing a large SQL insert for every diagnostic event, but they are not free: disk space, I/O, rotation, retention and access controls still matter. When running on several servers or containers, use central log shipping instead of relying on one host's local files. Rate-limit repetitive error events and never dump whole authenticated request objects into logs.

The `days` setting controls Laravel's daily file rotation retention for this channel; separately define database audit retention, backup rules and access permissions appropriate to your organisation. Retention is not necessarily forever, particularly where personal information is involved. For South African deployments, assess POPIA obligations and actual operational requirements.

9. How to test the complete correlation flow

Start by confirming the application's installed Monolog major version and testing this formatter in staging. Set `LOG_CHANNEL=diagnostic`, then clear the cached configuration and restart workers after deployment:

bash
php artisan config:clear
php artisan queue:restart

Call an authenticated API endpoint and inspect its `X-Correlation-ID` response header. Check a JSON diagnostic log entry, then check that a relevant business audit record contains the identical UUID in `reference`.

Trigger a controlled error and verify that both the exception diagnostic entry and error response carry the ID. Dispatch a job using `sync`, then use an asynchronous test queue and confirm the job keeps the originating UUID. Process a second job with a different UUID to ensure worker context does not leak. Finally, fake a trusted outbound HTTP request and verify the transmitted correlation header without contacting a real payment provider.

Be aware that middleware, scheduled commands, direct database queries and third-party log channels outside this configured flow will not automatically receive a correlation ID. Extend the same explicit propagation rules wherever necessary.

Final recommendation

For Laravel 8 APIs, use Monolog JSON files for short-lived technical diagnostics and MySQL for compact, queryable business audit events. Connect them with a request-level UUID carried in a response header, database `reference` field, job payload and trusted outbound API headers.

This provides better separation of concerns than storing complete request bodies, headers and traces in a single growing MySQL table. It also creates a sensible foundation for centralised observability and a future Laravel upgrade, without introducing new packages today.

Official references: Laravel 8 logging and Monolog tap configuration, Laravel 8 queue middleware, Laravel 8 HTTP client, and Laravel 8 release support policy.

WhatsApp us