• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

使用中间件记录Laravel慢请求

php 搞代码 4年前 (2022-02-28) 23次浏览 已收录 0个评论

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

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

<code class="PHP"><?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 未定义可在入口文件中定义。

<code class="PHP">define('LARAVEL_START', microtime(true));

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

<code class="PHP"><?php
namespace App\Http;

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

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

<code class="PHP">[2022-02-15 20:53:30] beta.WARNING: LONG_REQUEST GET [http://cms.demo.tecmz.com] 2140.96ms []

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:使用中间件记录Laravel慢请求
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址