笔记:中间件 middleware
中间件主要是提供了一种方便的机制用于过滤进入应用程序的 HTTP 请求。摘自文档
不仅可以过滤 HTTP 请求(前置中间件),也可用于记录日志(后置中间件),添加任务(Terminable中间件) 等。
命令行:php artisan make:middleware TestMiddleware
示例:
public function handle($request, Closure $next)
{
//请求执行之前,过滤http请求
Log::info('请求之前过滤http请求', []);
$response = $next($request);
//请求执行之后
$response->header('Token', 'this is add token!'); //设置响应头的token
$response->headers->set('Token1', 'this is add token1!'); //设置响应头的token
$response->withHeaders([
'Token2' => 'this is add token2!',
]);
Log::info('controller return 之后', [1, 2, 3]);
//响应
return $response;
}
基于terminate中间件实现慢请求日志:
public function terminate($request, $response)
{
$slowRequest = config('request.slow_request_time');
$useTime = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];
$log = [
'url' => $request->url(),
'method' => $request->method(),
'path' => $request->path(),
'headers' => $request->headers->all(),
'params' => $request->all(),
'clientIps' => $request->getClientIps()
];
$info = $request->path() . ' => userTime:' . $useTime * 1000 . 'ms';
if ($slowRequest && $useTime > $slowRequest) {
Log::channel('reqSlowLog')->info($info, $log);
} else {
Log::channel('reqLog')->info($info, $log);
}
}
配置文件request.php添加配置:
// 慢请求日志时间
'slow_request_time' => env('SLOW_REQUEST_TIME', 0),
本作品采用《CC 协议》,转载必须注明作者和本文链接