ENGINEERING JOURNAL

Structured JSON Logging with Correlation IDs in Laravel

Trace a Laravel request through the web process and the queue with structured JSON logs and one correlation ID per request.

THE ARTICLE 01 — 03

A request hits your Laravel API, queues a job, the job touches the database, and something fails. You open the log and find three separate lines that look unrelated. Which job belonged to which request? Which user? You cannot tell, because every line is a flat string with no shared identifier. Structured JSON logging with a correlation ID fixes this. One ID follows the request through the web process, the queue, and every log line in between, so you can pull the whole story with one command.

What structured logging actually changes

Laravel's default log line is human readable text. That is fine for a single server you read by eye. It breaks down the moment you need to search, filter, or ship logs to a central place. A JSON log line is a record with named fields: message, level, channel, context, and timestamp. You can filter on any field instead of grepping for a substring and hoping the format never changes. You do not need a logging platform to benefit: the jq command line tool is enough to query JSON logs on a server.

Switch the single channel in config/logging.php to the Monolog JSON formatter:

'single' => [
    'driver' => 'single',
    'path' => storage_path('logs/laravel.log'),
    'level' => env('LOG_LEVEL', 'debug'),
    'formatter' => Monolog\Formatter\JsonFormatter::class,
],

From that point on, every log call writes one JSON object per line. Do not change the log format on a whim later: dashboards and your own habits depend on the shape staying stable.

Generate one correlation ID per request

A correlation ID is a random string assigned when a request arrives. If the caller already sent one in an X-Correlation-Id header, reuse it, so the ID survives across services. Otherwise generate a UUID. A small middleware does the job:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

class CorrelationId
{
    public function handle(Request $request, Closure $next): Response
    {
        $id = $request->header('X-Correlation-Id') ?: (string) Str::uuid();

        Log::withContext(['correlation_id' => $id]);

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

        return $response;
    }
}

Register it in bootstrap/app.php so it runs on every request:

->withMiddleware(function (Middleware $middleware) {
    $middleware->append(CorrelationId::class);
})

Returning the ID in the response header is not decoration. When a user reports a problem, they can paste the header value, and you can look up exactly what happened.

Put the ID in every log line automatically

The key call is Log::withContext(). Anything you add there is merged into the context field of every log record for the rest of that request. You set it once in the middleware, and you never pass the ID around by hand in controllers or services. A log call like this is all you write:

Log::info('Claim submitted', ['claim_id' => $claim->id, 'amount' => $claim->amount]);

The line that lands in the log carries both your fields and the correlation ID, because the context was set once upstream. Add request-scoped facts the same way when they are cheap and stable: the authenticated user ID or the tenant organization ID. Never add passwords, tokens, API keys, or full request bodies. A log line with a secret in it is a secret stored in plain text on disk, and it will be copied into every backup and log archive you ever make.

Make the ID survive the queue

This is the step most people skip, and it is the step that makes the whole thing useful. A queued job runs in a different process, possibly on a different server. The request context does not follow it. You have to carry the ID in the job payload yourself. Store it on the job when you dispatch it:

ProcessClaim::dispatch($claim, Log::sharedContext()['correlation_id'] ?? null);

Then restore it at the start of the job's handle() method:

public function handle(): void
{
    if ($this->correlationId) {
        Log::withContext(['correlation_id' => $this->correlationId]);
    }

    // ... job work, all logged under the same ID
}

Now the web request, the queued job, and any job the first job dispatches can all be traced with one value. If a job fails and lands in failed_jobs, the correlation ID in its log lines tells you which request started the chain.

Reading the logs with jq

With the ID in hand, the lookup is one command. Show every line for a single request:

jq -c 'select(.context.correlation_id == "550e8400-e29b-41d4-a716-446655440000")' storage/logs/laravel.log

Count errors per correlation ID to find the noisiest requests:

jq -r 'select(.level_name == "ERROR") | .context.correlation_id' storage/logs/laravel.log | sort | uniq -c | sort -rn | head

Follow one request end to end across the web log and the queue worker log, and you will see the request arrive, the job dispatch, the job run, and the failure, all in sequence. This is the same technique I use when I am debugging a slow API endpoint: the correlation ID narrows a pile of logs down to the one request that matters.

What to log, and what to leave out

Structured logging only helps if the fields are consistent. Agree on a small set of field names and use them everywhere: correlation_id, user_id, organization_id, and the ID of the thing being processed, like claim_id or order_id. Do not invent a new field name for the same idea in each file. Log state changes, external calls, and failures with the values needed to reproduce them. Do not log full payloads, full responses, or anything a user typed into a password field. Keep the message short and human readable, and put the machine readable facts in the context array.

The takeaway

Structured JSON logging turns your log file into a database you can query, and a correlation ID turns scattered lines into one story. The setup is a middleware, a formatter change, and a habit of carrying the ID into queued jobs. Start with the web request only if you have to, but do not stop there: the queue is where the ID pays for itself, because that is where the request you are debugging no longer exists. Add the header, return it to the caller, and the next time something fails in production, you will find the answer with one command.

Muhammad Aqib ← ALL ARTICLES
KEEP EXPLORING

More ideas.
Better engineering.

Explore the journal ↗