Laravel8自定义json日志记录HTTP请求

IT小马

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);
阅读 254

IT小马の菜园
IT菜鸟的学习博客

版本控制:git

1k 声望
19 粉丝
0 条评论

版本控制:git

1k 声望
19 粉丝
文章目录
宣传栏