1

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);

IT小马
1.2k 声望166 粉丝

Php - Go - Vue - 云原生