Trung bình DevOps

Structured logging và request ID xuyên service: log JSON, Laravel Context và middleware

Thôi grep đống log text lộn xộn. Ghi event dạng JSON, gắn cùng một request ID cho mọi dòng, và truyền nó qua job lẫn các service khác bằng Laravel Context.

17 Th11, 2026 12 phút Cập nhật 23 Th10, 2026 10 Khối code
Sơ đồ
graph LR A[Client] --> B[Load balancer] B -->|X-Request-Id| C[Middleware Laravel] C --> D[Context request_id] D --> E[Log JSON] D --> F[Job trong queue] F --> E C -->|header X-Request-Id| G[Service thanh toán] G --> E E --> H[Tìm theo request_id]

Một khách báo checkout bị lỗi lúc 09:00. Mở log ra thì thấy hai trăm dòng "Payment failed" trong đúng phút đó, xen kẽ với log load giỏ hàng, webhook và queue worker từ sáu container. Dòng nào là của chị khách? Cảnh báo "Gateway timeout" nào đi với lỗi nào? Cái job gửi xác nhận chạy ba giây sau có phải từ cùng request đó không? Với log dạng text thường, mình chỉ biết grep, đoán, rồi bỏ cuộc.

Có hai thói quen giải quyết chuyện này. Structured log ghi mỗi entry thành một object JSON có field đặt tên rõ ràng, nhờ vậy hệ thống log lọc được theo order_id hay level thay vì so chuỗi con. Correlation ID đóng dấu cùng một request_id lên mọi entry sinh ra từ một request đi vô, xuyên suốt HTTP request, các job nó đẩy vô queue và các service nó gọi. Kết hợp lại, "grep rồi đoán" biến thành đúng một câu query.

Từ dòng text sang event

Đây là thứ đa số app Laravel log ra theo mặc định:

[2026-11-17 09:00:01] production.ERROR: Payment failed {"order":991}
[2026-11-17 09:00:01] production.INFO: Cart loaded
[2026-11-17 09:00:01] production.ERROR: Payment failed {"order":992}
[2026-11-17 09:00:02] production.WARNING: Gateway timeout

Order ID bị chôn trong message, dòng timeout không dính dáng gì tới lỗi nào, và không có gì cho biết request nào sinh ra dòng nào. Cũng mấy event đó nhưng ở dạng structured thì như vầy (mỗi event một dòng, format đẹp chỉ để người đọc):

{"message":"Payment failed","context":{"order_id":991,"gateway":"stripe","duration_ms":8012},"level_name":"ERROR","channel":"production","datetime":"2026-11-17T09:00:01.412+00:00","extra":{"request_id":"01JD2Z8Q4M7X","user_id":7,"route":"checkout.pay"}}

Giờ context giữ thông tin về chính event này, còn extra giữ thông tin chung của request mà event xảy ra trong đó: request ID, user, route. Field nào cũng index được. "Mọi lỗi của user 7 trong một giờ qua" hay "mọi dòng của request 01JD2Z8Q4M7X" trở thành query đơn giản.

ID đi qua hệ thống ra sao

ID chỉ được tạo một lần ở rìa hệ thống, sau đó chỉ được chép đi tiếp:

graph LR A[Client] --> B[Load balancer] B -->|X-Request-Id| C[Middleware Laravel] C --> D[Context request_id] D --> E[Log JSON] D --> F[Job trong queue] F --> E C -->|header X-Request-Id| G[Service thanh toán] G --> E E --> H[Tìm theo request_id]

Nếu load balancer hay ingress đã tạo sẵn ID (nhiều cái có, thường là X-Request-Id), xài lại nó để access log của tụi nó khớp với log của app. Nếu chưa có thì app tự tạo. Mọi lời gọi đi ra đều chuyển tiếp ID, và service nào cũng log nó dưới cùng một tên field.

Ghi log JSON trong Laravel

Monolog có sẵn JsonFormatter. Cho một channel ghi ra stderr với formatter đó; trong container, stdout và stderr chính là thứ platform thu thập:

// config/logging.php (excerpt)
use Monolog\Formatter\JsonFormatter;
use Monolog\Handler\StreamHandler;

return [
    'default' => env('LOG_CHANNEL', 'stack'),

    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => explode(',', env('LOG_STACK', 'json')),
            'ignore_exceptions' => false,
        ],

        // One JSON object per line on stderr: the container runtime ships it,
        // the log platform (Loki, ELK, CloudWatch, Datadog) indexes the fields.
        'json' => [
            'driver' => 'monolog',
            'level' => env('LOG_LEVEL', 'info'),
            'handler' => StreamHandler::class,
            'handler_with' => ['stream' => 'php://stderr'],
            'formatter' => JsonFormatter::class,
        ],
    ],
];

Ghi ra stderr thay vì storage/logs/laravel.log còn dẹp luôn một vấn đề kinh điển trên production: file log làm đầy ổ đĩa của container vì không có gì rotate nó.

Gán request ID bằng middleware và Context

Laravel 11 giới thiệu facade Context, và đây đúng là công cụ cho việc này. Thứ gì mình Context::add() sẽ được gắn vô mọi bản ghi log trong request đó, và còn được serialize kèm job trong queue, nên log của worker mang đúng mấy giá trị đó. Log::withContext() vẫn còn, nhưng nó chỉ tác động lên một log channel trong request hiện tại và không đi theo job.

namespace App\Http\Middleware;

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

final class AssignRequestId
{
    public const HEADER = 'X-Request-Id';

    public function handle(Request $request, Closure $next): Response
    {
        $requestId = $this->resolve($request->headers->get(self::HEADER));

        // Context data is attached to every log record and travels into queued jobs.
        Context::add('request_id', $requestId);
        Context::add('route', $request->route()?->getName());
        Context::add('method', $request->method());

        $response = $next($request);
        $response->headers->set(self::HEADER, $requestId);

        return $response;
    }

    private function resolve(?string $incoming): string
    {
        $incoming = trim((string) $incoming);

        // Accept an upstream ID only if it is short and boring; never log arbitrary input.
        return preg_match('/^[A-Za-z0-9._-]{8,64}$/', $incoming) === 1
            ? $incoming
            : (string) Str::ulid();
    }
}

Đăng ký nó đứng đầu stack, để kể cả lỗi xác thực hay bị chặn rate limit cũng được log kèm ID:

// bootstrap/app.php
use App\Http\Middleware\AssignRequestId;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(web: __DIR__.'/../routes/web.php', api: __DIR__.'/../routes/api.php')
    ->withMiddleware(function (Middleware $middleware): void {
        // Prepend so even early failures (auth, throttling) are logged with the ID.
        $middleware->prepend(AssignRequestId::class);
    })
    ->create();

Validate header gửi lên không phải là đa nghi quá mức. Header đó đến từ client. Không kiểm tra pattern, người ta có thể gửi một giá trị 10 KB, hoặc một giá trị chứa ký tự xuống dòng và mảnh JSON nhằm giả mạo thêm entry trong các format log theo dòng. Giá trị nào không phải một token ngắn, nhàm chán thì thay bằng cái mới.

Truyền ID qua job và service khác

Bên trong app, thêm thông tin chung một lần rồi log event kèm field riêng của nó:

use App\Jobs\SendOrderConfirmation;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Facades\Log;

// In a controller or action, after authentication:
Context::add('user_id', $request->user()?->id);

// Per-call context: the facts about THIS event, as fields, not baked into the message.
Log::info('Order placed', [
    'order_id' => $order->id,
    'total_cents' => $order->total_cents,
    'items' => $order->items->count(),
]);

// The job is serialized with the current Context. When a worker runs it,
// its logs carry the same request_id as the HTTP request that queued it.
SendOrderConfirmation::dispatch($order->id);

// Context for this log channel only, for the rest of the request:
Log::withContext(['tenant_id' => $tenant->id]);

Với các lời gọi sang service khác, chuyển tiếp ID tự động thay vì nhớ gắn ở từng chỗ gọi. Http::globalRequestMiddleware() áp dụng cho mọi request đi qua HTTP client của Laravel:

namespace App\Providers;

use Illuminate\Support\Facades\Context;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\ServiceProvider;
use Psr\Http\Message\RequestInterface;

final class ObservabilityServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Every outgoing call made with the Http client forwards the current ID,
        // so the next service can log under the same request_id.
        Http::globalRequestMiddleware(function (RequestInterface $request): RequestInterface {
            $id = Context::get('request_id');

            return $id === null ? $request : $request->withHeader('X-Request-Id', $id);
        });
    }
}

Service nhận request làm y chang trong stack của nó. Ở Node.js, AsyncLocalStorage đóng vai trò giống Context của Laravel: giữ dữ liệu theo request xuyên qua các await mà không cần truyền qua từng hàm:

// payments-service/src/request-context.js (Node 22, Express 5, pino)
const { AsyncLocalStorage } = require('node:async_hooks')
const { randomUUID } = require('node:crypto')
const pino = require('pino')

const storage = new AsyncLocalStorage()
const baseLogger = pino({ base: { service: 'payments' } })

function requestContext(req, res, next) {
  const incoming = req.get('x-request-id') ?? ''
  const requestId = /^[A-Za-z0-9._-]{8,64}$/.test(incoming) ? incoming : randomUUID()

  res.set('x-request-id', requestId)
  storage.run({ logger: baseLogger.child({ request_id: requestId }) }, next)
}

const log = () => storage.getStore()?.logger ?? baseLogger

module.exports = { requestContext, log }

Khi có sự cố, một câu query kéo ra nguyên câu chuyện, đúng thứ tự, từ mọi service:

# Loki / LogQL: everything that happened for one request, across services
{env="production"} | json | request_id="01JD2Z8Q4M7X"

# CloudWatch Logs Insights
fields @timestamp, service, level_name, message
| filter extra.request_id = "01JD2Z8Q4M7X"
| sort @timestamp asc

Nếu đã chạy OpenTelemetry, xài luôn trace ID của nó (từ header W3C traceparent) làm correlation ID và log dưới tên trace_id, vậy là log nối thẳng được sang trace. Pattern y hệt; chỉ khác tên header và tên field.

Kiểm thử middleware request ID

Middleware có hai nhiệm vụ đáng test: xài lại ID hợp lệ từ phía trước, và từ chối mọi thứ khác. Feature test bằng Pest cover được cả hai, kể cả việc ID trong Context khớp với ID trả về cho client:

use Illuminate\Support\Facades\Context;
use Illuminate\Support\Facades\Route;

beforeEach(function () {
    Route::get('/_test/ping', fn () => ['request_id' => Context::get('request_id')]);
});

it('reuses a well-formed incoming request id', function () {
    $this->getJson('/_test/ping', ['X-Request-Id' => 'edge-7f3a9c21'])
        ->assertHeader('X-Request-Id', 'edge-7f3a9c21')
        ->assertJsonPath('request_id', 'edge-7f3a9c21');
});

it('replaces a malicious incoming id with a fresh one', function () {
    $response = $this->getJson('/_test/ping', ['X-Request-Id' => "x\n{\"level\":\"EMERGENCY\"}"]);

    $id = $response->headers->get('X-Request-Id');

    expect($id)->toMatch('/^[0-9A-HJKMNP-TV-Z]{26}$/')
        ->and($response->json('request_id'))->toBe($id);
});

Cũng nên có một test cho mỗi dòng log quan trọng, assert rằng các field mình đặt alert thật sự tồn tại. Dashboard và alert hỏng âm thầm khi ai đó đổi order_id thành orderId.

Những lỗi hay gặp

  • Nhồi dữ liệu vô message. "Payment failed for order 991" thì không group hay lọc được. Giữ message cố định, đưa biến vô field context.
  • Log secret và dữ liệu cá nhân. Request body, header Authorization, token, số thẻ đầy đủ không có chỗ trong log. Log ID chứ đừng log payload, và redact các key nhạy cảm đã biết trong một Monolog processor làm lưới an toàn.
  • Mỗi service tự tạo ID mới. Vậy thì chẳng có gì nối với nhau được. Chỉ rìa hệ thống tạo; mọi chỗ khác chỉ chuyển tiếp.
  • Tên field không thống nhất. request_id, requestId và req_id ở ba service là ba câu query. Thống nhất tên một lần và ghi lại.
  • Quên phần chạy nền. Scheduled command và job không bắt nguồn từ request thì không có ID. Thêm một cái ở đầu mỗi command (Context::add('request_id', (string) Str::ulid())) để log của tụi nó vẫn gom nhóm được.
  • Label có cardinality cao. Ở các hệ kiểu Loki, request_id phải là field được parse, không phải stream label; xài nó làm label sẽ tạo một stream cho mỗi request và làm khổ kho log.

Khi nào nên xài, khi nào không

Xài structured log JSON và request ID cho mọi thứ chạy trên hơn một process: nhiều web container, queue worker, hoặc nhiều service. Setup chỉ gồm một middleware, một cấu hình channel và một hook cho HTTP client, và nó hoàn vốn ngay ở sự cố đầu tiên.

Một app nhỏ chạy trên một server, một người đọc bằng tail -f, có thể sống với text thường một thời gian; JSON đọc thô khó hơn. Kể cả vậy, thêm request ID vô format dòng log cũng không tốn gì. Và đừng nhầm correlation ID với tracing: nó cho biết dòng nào thuộc về nhau, chứ không cho biết mỗi bước tốn bao lâu. Khi câu hỏi là độ trễ giữa các service, thêm tracing bằng OpenTelemetry và giữ log liên kết với trace qua ID.

Thử thách tương tác

Thử thách

Luyện tập ngay điều vừa học. Viết lời giải, mở gợi ý nếu bí.

Đề bài

Viết hai phần của một structured logger. Thứ nhất, resolve_request_id(incoming, generate): trim giá trị header gửi lên (có thể là null/None) và trả về nó nếu toàn bộ chuỗi khớp ^[A-Za-z0-9._-]{8,64}$; ngược lại trả về generate(). Thứ hai, class StructuredLogger có constructor nhận một hàm clock trả về chuỗi timestamp. withContext(array $context) (Python: with_context(dict)) merge vô context dùng chung; giá trị sau thắng, thứ tự key cũ được giữ. log(level, message, context = []) trả về MỘT dòng JSON (không có ký tự xuống dòng). Level hợp lệ là debug, info, warning, error; level khác thì throw InvalidArgumentException (Python: ValueError). Object JSON bắt đầu bằng ts (giá trị clock), level và message, sau đó là context dùng chung merge với context của lần gọi (context của lần gọi thắng khi trùng key; key giữ vị trí đầu tiên của nó). Key trong context tên ts, level hoặc message bị bỏ qua, không bao giờ ghi đè các field dành riêng. Giá trị của key tên password, token, authorization hoặc cookie, so sánh không phân biệt hoa thường, được thay bằng chuỗi [REDACTED] (giữ nguyên cách viết key gốc).

Code khởi tạo

php
function resolve_request_id(?string $incoming, Closure $generate): string
{
    // TODO: trim $incoming; keep it if it matches ^[A-Za-z0-9._-]{8,64}$, otherwise return $generate()
    return '';
}

final class StructuredLogger
{
    private const LEVELS = ['debug', 'info', 'warning', 'error'];
    private const SENSITIVE = ['password', 'token', 'authorization', 'cookie'];

    /** @var array<string, mixed> */
    private array $shared = [];

    public function __construct(private Closure $clock) {}

    /** @param array<string, mixed> $context */
    public function withContext(array $context): void
    {
        // TODO: merge $context into the shared context (later values win)
    }

    /** @param array<string, mixed> $context */
    public function log(string $level, string $message, array $context = []): string
    {
        // TODO: reject unknown levels with InvalidArgumentException
        // TODO: build ts, level, message, then shared + call context (call wins, reserved keys cannot be overridden)
        // TODO: redact sensitive keys (case-insensitive) and return one JSON line
        return '{}';
    }
}
python
import json
import re
from typing import Any, Callable

LEVELS = {"debug", "info", "warning", "error"}
SENSITIVE = {"password", "token", "authorization", "cookie"}


def resolve_request_id(incoming: str | None, generate: Callable[[], str]) -> str:
    # TODO: strip incoming; keep it if it matches [A-Za-z0-9._-]{8,64}, else return generate()
    raise NotImplementedError


class StructuredLogger:
    def __init__(self, clock: Callable[[], str]) -> None:
        self.clock = clock
        self.shared: dict[str, Any] = {}

    def with_context(self, context: dict[str, Any]) -> None:
        # TODO: merge context into self.shared (later values win)
        raise NotImplementedError

    def log(self, level: str, message: str, context: dict[str, Any] | None = None) -> str:
        # TODO: ValueError for unknown levels; ts, level, message first; then shared + context
        #       (context wins, reserved keys cannot be overridden); redact sensitive keys; one JSON line
        raise NotImplementedError

Lời giải của bạn

Gợi ý

Đã mở hết gợi ý
Gợi ý 1

Regex phải khớp nguyên chuỗi, nên PHP xài anchor còn Python xài re.fullmatch

Gợi ý 2

Dựng record với các field dành riêng trước, rồi lặp qua context đã merge và bỏ qua key đã có

Gợi ý 3

Spread [...$a, ...$b] của PHP và {**a, **b} của Python đều giữ vị trí đầu của key nhưng lấy giá trị sau

Lời giải · php
function resolve_request_id(?string $incoming, Closure $generate): string
{
    $candidate = trim((string) $incoming);

    if (preg_match('/^[A-Za-z0-9._-]{8,64}$/', $candidate) === 1) {
        return $candidate;
    }

    return $generate();
}

final class StructuredLogger
{
    private const LEVELS = ['debug', 'info', 'warning', 'error'];
    private const SENSITIVE = ['password', 'token', 'authorization', 'cookie'];

    /** @var array<string, mixed> */
    private array $shared = [];

    public function __construct(private Closure $clock) {}

    /** @param array<string, mixed> $context */
    public function withContext(array $context): void
    {
        $this->shared = [...$this->shared, ...$context];
    }

    /** @param array<string, mixed> $context */
    public function log(string $level, string $message, array $context = []): string
    {
        if (! in_array($level, self::LEVELS, true)) {
            throw new InvalidArgumentException("Unknown level {$level}");
        }

        $record = ['ts' => ($this->clock)(), 'level' => $level, 'message' => $message];

        foreach ([...$this->shared, ...$context] as $key => $value) {
            if (array_key_exists($key, $record)) {
                continue;
            }

            $record[$key] = in_array(strtolower((string) $key), self::SENSITIVE, true) ? '[REDACTED]' : $value;
        }

        return json_encode($record, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
    }
}
Lời giải · python
import json
import re
from typing import Any, Callable

LEVELS = {"debug", "info", "warning", "error"}
SENSITIVE = {"password", "token", "authorization", "cookie"}


def resolve_request_id(incoming: str | None, generate: Callable[[], str]) -> str:
    candidate = (incoming or "").strip()
    if re.fullmatch(r"[A-Za-z0-9._-]{8,64}", candidate):
        return candidate
    return generate()


class StructuredLogger:
    def __init__(self, clock: Callable[[], str]) -> None:
        self.clock = clock
        self.shared: dict[str, Any] = {}

    def with_context(self, context: dict[str, Any]) -> None:
        self.shared = {**self.shared, **context}

    def log(self, level: str, message: str, context: dict[str, Any] | None = None) -> str:
        if level not in LEVELS:
            raise ValueError(f"Unknown level {level}")
        record: dict[str, Any] = {"ts": self.clock(), "level": level, "message": message}
        for key, value in {**self.shared, **(context or {})}.items():
            if key in record:
                continue
            record[key] = "[REDACTED]" if key.lower() in SENSITIVE else value
        return json.dumps(record, separators=(",", ":"), ensure_ascii=False)

Cùng chủ đề DevOps