给ThinkPHP添加接口Trace

在日常开发中,有时候需要调试接口,没法使用Trace跟踪代码,今天根据官方的Trace改装了个可以在api接口里面获取Trace信息的中间,直接注册就可以使用;

php 复制代码
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare(strict_types=1);

namespace app\common\middleware;

use Closure;
use think\App;
use think\Config;
use think\event\LogWrite;
use think\Request;
use think\Response;
use think\response\Redirect;

/**
 * 页面Trace中间件
 */
class JsonTraceDebug
{

    /**
     * Trace日志
     * @var array
     */
    protected $log = [];

    /**
     * 配置参数
     * @var array
     */
    // protected $config = [];

    protected $config = [
        'tabs' => ['base' => '基本', 'file' => '文件', 'info' => '流程', 'notice|error' => '错误', 'sql' => 'SQL', 'debug|log' => '调试'],
    ];

    /** @var App */
    protected $app;

    public function __construct(App $app, Config $config)
    {
        $this->app = $app;
    }

    /**
     * 页面Trace调试
     * @access public
     * @param Request $request
     * @param Closure $next
     * @return void
     */
    public function handle($request, Closure $next)
    {
        $debug = $this->app->isDebug();

        // 注册日志监听
        if ($debug) {
            $this->log = [];
            $this->app->event->listen(LogWrite::class, function ($event) {
                if (empty($this->config['channel']) || $this->config['channel'] == $event->channel) {
                    $this->log = array_merge_recursive($this->log, $event->log);
                }
            });
        }

        $response = $next($request);

        // Trace调试注入
        if ($debug) {
            $data = $response->getContent();
            if ($response instanceof Redirect) {
                //TODO 记录
            } else {
                $log = $this->app->log->getLog('');
                $log = array_merge_recursive($this->log, $log);
                $trace = $this->output($response, $log);
                $data = json_decode($data, true);
                $data['trace'] = $trace;
            }
            $response->content(json_encode($data));
        }

        return $response;
    }

    /**
     * 调试输出接口
     * @access public
     * @param  Response  $response Response对象
     * @param  array     $log 日志信息
     * @return string|bool
     */
    public function output(Response $response, array $log = [])
    {
        $request = $this->app->request;
        $contentType = $response->getHeader('Content-Type');
        if (!empty($contentType) && strpos($contentType, 'html') !== false) {
            return false;
        } elseif ($response->getCode() == 204) {
            return false;
        }

        // 获取基本信息
        $runtime = number_format(microtime(true) - $this->app->getBeginTime(), 10, '.', '');
        $reqs = $runtime > 0 ? number_format(1 / $runtime, 2) : '∞';
        $mem = number_format((memory_get_usage() - $this->app->getBeginMem()) / 1024, 2);

        if ($request->host()) {
            $uri = $request->protocol() . ' ' . $request->method() . ' : ' . $request->url(true);
        } else {
            $uri = 'cmd:' . implode(' ', $_SERVER['argv']);
        }

        // 页面Trace信息
        $base = [
            '请求信息' => date('Y-m-d H:i:s', $request->time() ?: time()) . ' ' . $uri,
            '运行时间' => number_format((float) $runtime, 6) . 's [ 吞吐率:' . $reqs . 'req/s ] 内存消耗:' . $mem . 'kb 文件加载:' . count(get_included_files()),
            '查询信息' => $this->app->db->getQueryTimes() . ' queries',
            '缓存信息' => $this->app->cache->getReadTimes() . ' reads,' . $this->app->cache->getWriteTimes() . ' writes',
        ];

        if (isset($this->app->session)) {
            $base['会话信息'] = 'SESSION_ID=' . $this->app->session->getId();
        }

        $info = $this->getFileInfo();

        // 页面Trace信息
        $trace = [];
        foreach ($this->config['tabs'] as $name => $title) {
            $name = strtolower($name);
            switch ($name) {
                case 'base': // 基本信息
                    $trace[$title] = $base;
                    break;
                case 'file': // 文件信息
                    $trace[$title] = $info;
                    break;
                default: // 调试信息
                    if (strpos($name, '|')) {
                        // 多组信息
                        $names = explode('|', $name);
                        $result = [];
                        foreach ($names as $item) {
                            $result = array_merge($result, $log[$item] ?? []);
                        }
                        $trace[$title] = $result;
                    } else {
                        $trace[$title] = $log[$name] ?? '';
                    }
            }
        }
        $trace['SQL'] = array_reverse($trace['SQL']);
        return $trace;
    }


    /**
     * 获取文件加载信息
     * @access protected
     * @return integer|array
     */
    protected function getFileInfo()
    {
        $files = get_included_files();
        $info = [];

        foreach ($files as $key => $file) {
            $info[] = $file . ' ( ' . number_format(filesize($file) / 1024, 2) . ' KB )';
        }

        return $info;
    }
}
相关推荐
许苑向上30 分钟前
Java八股文(下)
java·开发语言
菜鸟一枚在这35 分钟前
深入解析设计模式之单例模式
开发语言·javascript·单例模式
独孤求败Ace38 分钟前
第44天:Web开发-JavaEE应用&反射机制&类加载器&利用链&成员变量&构造方法&抽象方法
java·开发语言
计算机-秋大田1 小时前
基于Spring Boot的农产品智慧物流系统设计与实现(LW+源码+讲解)
java·开发语言·spring boot·后端·spring·课程设计
matlabgoodboy1 小时前
Matlab代编电气仿真电力电子电机控制自动化新能源微电网储能能量
开发语言·matlab·自动化
镰圈量化1 小时前
当电脑上有几个python版本Vscode选择特定版本python
开发语言·vscode·python
背太阳的牧羊人2 小时前
RAG检索中使用一个 长上下文重排序器(Long Context Reorder) 对检索到的文档进行进一步的处理和排序,优化输出顺序
开发语言·人工智能·python·langchain·rag
ITPUB-微风2 小时前
美团MTSQL特性解析:技术深度与应用广度的完美结合
java·服务器·开发语言
Want5952 小时前
C/C++跳动的爱心
c语言·开发语言·c++
水瓶丫头站住2 小时前
Qt中QDockWidget的使用方式
开发语言·qt