1.自定义日志通道
vim config/logging.php
'request' => [
'driver' => 'daily',//按日期分隔日志
'path' => storage_path('logs/request.log'),
'tap' => [App\Logging\CustomizeFormatter::class],
'days' => 14,
],
2.自定义json解析
新建CustomizeFormatter
getHandlers() as $handler) {
$handler->setFormatter(new CustomizeJsonFormatter());
}
}
}
新建CustomizeJsonFormatter
$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);