关于php:使用中间件记录Laravel慢请求

4次阅读

共计 926 个字符,预计需要花费 3 分钟才能阅读完成。

一个零碎须要继续优化,日志尤为要害。通过巧用中间件记录零碎的慢申请,能够不必依赖任何监控型服务,定期剖析日志,从而优化零碎。

通过定义一个监控中间件,记录慢查问。

<?php

namespace ModStart\Core\Monitor;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ModStartMonitorMiddleware
{public function handle(Request $request, \Closure $next)
    {$response = $next($request);
        if (defined('LARAVEL_START')) {$time = round((microtime(true) - LARAVEL_START) * 1000, 2);
            $param = json_encode(\Illuminate\Support\Facades\Request::input());
            $url = $request->url();
            $method = $request->method();
            if ($time > 1000) {Log::warning("LONG_REQUEST $method [$url] ${time}ms $param");
            }
        }
        return $response;
    }
}

如果常量 LARAVEL_START 未定义可在入口文件中定义。

define('LARAVEL_START', microtime(true));

在零碎 Kernel 类中减少中间件到所有申请。

<?php
namespace App\Http;

class Kernel extends \Illuminate\Foundation\Http\Kernel
{
    protected $middleware = [
        \ModStart\Core\Monitor\ModStartMonitorMiddleware::class,
        // ...
    ];
}

这样就能够在日志中看到慢申请

[2022-02-15 20:53:30] beta.WARNING: LONG_REQUEST GET [http://cms.demo.tecmz.com] 2140.96ms []
正文完
 0