如何在请求中添加一个独特的HTTP X-Request-Id并在Symfony应用程序中访问它

560 阅读1分钟

使用下面的简单例子,为每个请求添加一个独特的HTTP X-Request-Id,并在Symfony应用程序中访问它。假设你有一个基于Nginx和PHP-FPM的Symfony应用程序。

Nginx配置

server {
    ...

    location ~ ^/index\.php(/|$) {
        ...
        fastcgi_param HTTP_X_REQUEST_ID $request_id;

        internal;
    }

    ...
}

config/services.yaml

parameters:
    env(HTTP_X_REQUEST_ID): ~

services:
    App\Controller\DockerController:
        tags: ['controller.service_arguments']
        arguments:
            $xRequestId: '%env(string:HTTP_X_REQUEST_ID)%'

DockerController

class DockerController
{
    private $xRequestId;

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

    public function index(Request $request): Response
    {
        print_r($_SERVER);
        print_r($request->headers->all());

        return new Response('X-Request-Id: '.$this->xRequestId);
    }
}

结果

Array
(
    ...
    [HTTP_X_REQUEST_ID] => c4c46e8c2d323d829dcb2ed1c5a3c48d
    ...
)

Array
(
    ...
    [x-request-id] => Array
        (
            [0] => c4c46e8c2d323d829dcb2ed1c5a3c48d
        )
    ...
)

X-Request-Id: c4c46e8c2d323d829dcb2ed1c5a3c48d