Bu örnekte, Symfony loglarına HTTP X-Request-Id bilgisini ekleyeceğiz, böylece hataları isteklere bağlamak daha kolay olacak.


Ön şartlar


Bir önceki yazıda söylenenleri yapın. Ayrıca Monolog kurulumunuda yaptığınızı varsayıyorum.


XRequestIdProcessor


declare(strict_types=1);

namespace App\Logger;

class XRequestIdProcessor
{
private $xRequestId;

public function __construct(?string $xRequestId)
{
$this->xRequestId = $xRequestId;
}

public function __invoke(array $record)
{
$record['context']['x_request_id'] = $this->xRequestId;

return $record;
}
}

# config/services.yaml
parameters:
env(HTTP_X_REQUEST_ID): ~

services:
App\Logger\XRequestIdProcessor:
arguments:
$xRequestId: '%env(string:HTTP_X_REQUEST_ID)%'
tags:
- { name: monolog.processor }

Sonuç


Eğer logların uygulamadaki var\log klasörü yerine Docker terminaline gitmelerini isterseniz, monolog config dosyalarında path: "php://stderr" girdisini kullanın.


Başarı


# Old Version
"[2019-03-05 21:28:23] request.INFO: Matched route "index".
{
"route":"index",
"route_parameters":{
"_route":"index",
"_controller":"App\\Controller\\DockerController::index"
},
"request_uri":"https://192.168.99.30:3043/",
"method":"GET"
} []"

# New Version
"[2019-03-05 21:44:30] request.INFO: Matched route "index".
{
"route":"index",
"route_parameters":{
"_route":"index",
"_controller":"App\\Controller\\DockerController::index"
},
"request_uri":"https://192.168.99.30:3043/",
"method":"GET",
"x_request_id":"11e201e793a6e96bb38387407be09f8d"
} []"

Hata


# Old Version
"[2019-03-05 21:59:19] php.CRITICAL: Uncaught Exception: Ohh Dear
{
"exception":"[object] (RuntimeException(code: 0): Ohh Dear at /app/src/Controller/DockerController.php:14)"
} []"

# New Version
"[2019-03-05 21:59:19] php.CRITICAL: Uncaught Exception: Ohh Dear
{
"exception":"[object] (RuntimeException(code: 0): Ohh Dear at /app/src/Controller/DockerController.php:14)",
"x_request_id":"a418e2ea71db77f999219769446dbdc4"
} []"