将HTTP X-Request-Id添加到Symfony日志中的实例

191 阅读1分钟

在这个例子中,我们将把HTTP X-Request-Id添加到Symfony日志中,这样就可以更容易地将错误与请求联系起来。

前提条件

请确保你做了这篇文章的内容。假设你也已经安装了Monolog

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 }

结果

如果你想让你的日志转到Docker终端而不是你的应用程序的var\log 文件夹,请在monolog配置文件中使用path: "php://stderr"

成功

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

错误

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