乐趣区

关于laravel:Laravel8自定义json日志记录HTTP请求

1. 自定义日志通道

vim config/logging.php

'request' => [
    'driver' => 'daily',// 按日期分隔日志
    'path' => storage_path('logs/request.log'),
    'tap' => [App\Logging\CustomizeFormatter::class],
    'days' => 14,
],

2. 自定义 json 解析

新建 CustomizeFormatter

<?php
namespace App\Logging;

class CustomizeFormatter
{
    /**
     * 自定义给定的日志实例。*
     * @param  \Illuminate\Log\Logger $logger
     * @return void
     */
    public function __invoke($logger)
    {foreach ($logger->getHandlers() as $handler) {$handler->setFormatter(new CustomizeJsonFormatter());
        }
    }
}

新建 CustomizeJsonFormatter

<?php
namespace App\Logging;

use Monolog\Formatter\JsonFormatter;

class CustomizeJsonFormatter extends JsonFormatter
{
    /**
     * 格式化
     *
     * @param array $record
     * @return string
     */
    public function format(array $record): string
    {
        $newRecord = ['datetime' => $record['datetime']->format('Y-m-d H:i:s'),
            'message' => $record['message'],
        ];

        if (!empty($record['context'])) {$newRecord = array_merge($newRecord, $record['context']);
        }
        $json = $this->toJson($this->normalize($newRecord), true) . ($this->appendNewline ? "\n" : '');

        return $json;
    }
}

3. 记录 HTTP 申请

创立中间件

php artisan make:middleware RequestLogMiddleware

配置全局拜访 vim app/Http/Kernel.php

protected $middleware = [
    ...
    \App\Http\Middleware\RequestLogMiddleware::class,
];

记录 HTTP 申请

$requestLog = ['ip' => $request->ips(),
    'method' => $request->method(),
    'status_code' => $response->getStatusCode(),
    'headers' => $request->header(),
    'url' => $request->url(),
    'query' => $request->query(),
    'params' => $request->all(),
    'response' => $response->getData(),];

4. 输入日志

\Log::channel('request')->info('REQUEST LOG', $requestLog);
退出移动版