使用中间件记录Laravel慢请求

 
更多

一个系统需要持续优化,日志尤为关键。通过巧用中间件记录系统的慢请求,可以不用依赖任何监控型服务,定期分析日志,从而优化系统。

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

<?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 []

打赏

本文固定链接: https://www.cxy163.net/archives/2557 | 绝缘体

该日志由 绝缘体.. 于 2025年09月28日 发表在 未分类 分类下, 你可以发表评论,并在保留原文地址及作者的情况下引用到你的网站或博客。
原创文章转载请注明: 使用中间件记录Laravel慢请求 | 绝缘体

使用中间件记录Laravel慢请求:等您坐沙发呢!

发表评论


快捷键:Ctrl+Enter