ThinkPHP在Debian中的性能监控方案
在Debian系统中,首先需要通过系统工具监控底层资源使用情况,为ThinkPHP应用性能问题定位提供基础数据:
top更直观,可实时查看CPU、内存、进程运行状态(如sudo apt install htop && htop)。vmstat 1 5每秒更新一次,共5次)。sysstat包),通过iostat -xz 1查看磁盘读写速度、I/O等待时间。netstat -tulnp显示所有TCP/UDP连接及对应进程,ss -tuln更简洁)。journalctl -u apache2查看Apache日志,journalctl --since "2025-11-01"查看指定时间范围日志)。composer require barryvdh/laravel-debugbar(ThinkPHP兼容)。config/app.php添加Barryvdh\Debugbar\ServiceProvider::class到providers数组)。app/middleware.php添加Barryvdh\Debugbar\Middleware\Debugbar::class),无需修改代码即可查看性能数据。pecl install xhprof),在ThinkPHP入口文件(如public/index.php)中添加Afk11\Xhprof\Xhprof::start()开启分析,结束时调用Afk11\Xhprof\Xhprof::end()结束并生成数据。git clone https://github.com/perftools/xhgui),配置MySQL存储分析数据,通过Web界面查看函数调用树、热点函数等信息,帮助定位性能瓶颈(如慢查询、重复计算)。通过ThinkPHP中间件记录请求耗时、内存使用等指标,写入日志或发送至监控系统:
php think make:middleware PerformanceMiddleware。handle方法中记录开始时间,响应后计算耗时并写入日志(如$start = microtime(true); $response = $next($request); $cost = microtime(true) - $start; \think\facade\Log::info("请求耗时:{$cost}秒");)。app/middleware.php中添加自定义中间件,全局生效。sudo apt install prometheus),配置prometheus.yml添加ThinkPHP应用作为抓取目标(如scrape_configs中配置targets: ['localhost:9090'])。think-prometheus)暴露性能指标(如请求数、响应时间、错误数),格式符合Prometheus要求。sudo apt install grafana),添加Prometheus数据源,创建面板展示ThinkPHP性能趋势(如请求延迟分布、内存使用率)。sudo apt install datadog-agent),配置datadog.yaml。composer require datadog/php-datadogstatsd),在代码中记录指标(如$datadog->timing('thinkphp.request.time', $cost_time)),发送至Datadog平台。config/log.php中level设置为['info', 'error']),记录应用运行信息(如请求日志、错误日志),便于后续分析。composer require sentry/sdk),记录异常堆栈、请求上下文,及时通知开发人员修复问题。