symfony中输出log为json格式,并在一次请求的log中添加唯一标识 标准码农 Symfony博客 227 views 输出log格式: ```json {"message":"Checking for authenticator support.","context":{"firewall_name":"main","authenticators":0},"level":100,"level_name":"DEBUG","channel":"security","datetime":"2023-08-16T02:37:55.332139+00:00","extra":{"token":"hDEbLk2glJZKKFUkkTmh39Zu5jeVufod","post":{"page":"1","limit":"10"},"get":[],"route_params":[]}} ``` ##### config/services.yaml ```yaml monolog.formatter.session_request: class: Monolog\Formatter\LineFormatter arguments: - "[%%datetime%%] [%%extra.token%%] %%channel%%.%%level_name%%: %%message%% %%context%% %%extra%%\n" App\Logger\SessionRequestProcessor: tags: - { name: monolog.processor } App\EventListener\ResponseListener: tags: - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse } ``` ##### config/packages/monolog.yaml ```yaml monolog: channels: - deprecation # Deprecations are logged in the dedicated "deprecation" channel when it exists when@dev: monolog: handlers: main: type: fingers_crossed action_level: error handler: nested excluded_http_codes: [ 404, 405 ] buffer_size: 50 # How many messages should be saved? Prevent memory leaks nested: type: stream path: php://stderr level: debug formatter: monolog.formatter.json console: type: console process_psr_3_messages: false channels: ["!event", "!doctrine", "!console"] file: type: stream level: debug formatter: 'monolog.formatter.json' when@test: monolog: handlers: main: type: fingers_crossed action_level: error handler: nested excluded_http_codes: [404, 405] channels: ["!event"] nested: type: stream path: "%kernel.logs_dir%/%kernel.environment%.log" level: debug when@prod: monolog: handlers: main: type: fingers_crossed action_level: error handler: nested excluded_http_codes: [404, 405] buffer_size: 50 # How many messages should be saved? Prevent memory leaks nested: type: stream path: php://stderr level: debug formatter: monolog.formatter.json console: type: console process_psr_3_messages: false channels: ["!event", "!doctrine"] deprecation: type: stream channels: [deprecation] path: php://stderr file: type: stream level: debug formatter: 'monolog.formatter.json' ``` ##### src/EventListener/ResponseListener.php ```php <?php namespace App\EventListener; use App\Logger\SessionRequestProcessor; use Symfony\Component\HttpKernel\Event\ResponseEvent; class ResponseListener { public function __construct( private SessionRequestProcessor $processor, ) {} public function onKernelResponse(ResponseEvent $event): void { $response = $event->getResponse(); $response->headers->add([ 'global-token' => $this->processor->getToken() ]); $event->setResponse($response); } } ``` ##### src/Logger/SessionRequestProcessor.php ```yaml <?php namespace App\Logger; use App\Lib\Tool\StringTool; use Monolog\LogRecord; use Symfony\Component\HttpFoundation\Request; class SessionRequestProcessor { private string $token = ""; // this method is called for each log record; optimize it to not hurt performance public function __invoke(LogRecord $record):LogRecord { if(!$this->token){ $this->token = StringTool::random(32); } $record->extra['token'] = $this->token; $record->extra['post'] = Request::createFromGlobals()->request->all(); $record->extra['get'] = Request::createFromGlobals()->query->all(); $record->extra['route_params'] = Request::createFromGlobals()->attributes->get('_route_params', []); return $record; } public function getToken(): string { if(!$this->token){ $this->token = StringTool::random(32); } return $this->token; } } ``` ##### src/Lib/Tool/StringTool.php ```php <?php namespace App\Lib\Tool; class StringTool { static public function random(int $n): string { $arr1 = range('a', 'z'); $arr2 = range('A', 'Z'); $arr3 = range('0', '9'); $array = array(...$arr1, ...$arr2, ...$arr3); $count = count($array); $rs = []; for ($i = 0; $i < $n; $i++) { $tmp = mt_rand(0, $count - 1); $rs[] = $array[$tmp]; } return implode('', $rs); } } ``` 最后在响应的header中查看global-token来查找全局token ![](https://phpzlc.com//upload/654b5cc8cb69e.png) 帮助PHPZlc项目! 与任何开源项目一样, 贡献代码 或 文档 是最常见的帮助方式, 但我们也有广泛的 赞助机会。 1 加入技术群 评论 去登录