Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

In this example we are going to add HTTP X-Request-Id to Symfony logs so that linking errors to requests would be easier.


Prerequisites


Make sure you do what this post does. Assuming that you've installed Monolog as well.


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 }

Result


If you want your logs to go to Docker terminal rather than the var\log folder of your application, use path: "php://stderr" in monolog config files.


Success


# 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"
} []"

Error


# 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"
} []"