Ubuntu环境下ThinkPHP性能监控的实施方法

ThinkPHP内置日志功能可记录请求时间、错误信息等基础性能数据,是监控的第一步。
application/config.php,设置日志类型为file(存储到runtime/log目录),并指定日志级别(如info、error):'log' => ['type'=> 'file','var_log_path' => './runtime/log','level' => ['info', 'error'],],thinkfacadeLog记录关键节点时间(如请求开始/结束):// 记录请求开始时间thinkfacadeLog::info('请求开始时间:' . date('Y-m-d H:i:s'));// 记录错误信息(如数据库查询失败)thinkfacadeLog::error('数据库查询失败:' . $e->getMessage());通过自定义中间件捕获每个请求的执行时间,适用于快速定位慢请求。
php think make:middleware PerformanceMiddleware生成中间件文件,编写逻辑记录耗时:namespace appmiddleware;use thinkfacadeLog;use thinkmiddlewareBaseMiddleware;class PerformanceMiddleware extends BaseMiddleware{public function handle($request, Closure $next){$start_time = microtime(true); // 记录开始时间$response = $next($request); // 执行请求$end_time = microtime(true); // 记录结束时间$cost_time = $end_time - $start_time; // 计算耗时Log::info('请求路径:' . $request->path() . ',耗时:' . $cost_time . '秒');return $response;}}application/middleware.php中添加中间件,使其全局生效:return [appmiddlewarePerformanceMiddleware::class,];集成专业监控工具可实现更全面的性能追踪(如响应时间、数据库查询、服务器资源),并支持报警功能。
composer require datadog/php-datadogstatsd;config/datadog.php,填写Datadog Agent地址和端口:return ['host' => 'localhost','port' => 8125,'namespace' => 'thinkphp_app','tags' => ['env:production'],];provider.php):$this->app->bind('datadog', function () {$config = config('datadog');return new DataDogDogStatsd($config);});$datadog = app('datadog');$start_time = microtime(true);// 业务逻辑(如数据库查询)$elapsed_time = microtime(true) - $start_time;$datadog->timing('controller.index.execution_time', $elapsed_time);sudo apt install newrelic-php5(或对应版本);newrelic.ini),设置应用名称和许可证密钥;public/index.php)中启动New Relic监控:if (extension_loaded('newrelic')) {newrelic_name_transaction('thinkphp_request');}使用专业分析工具深入代码层级,找出性能瓶颈(如慢函数、内存泄漏)。
sudo pecl install xhprof,并在php.ini中启用:extension=xhprof.soconfig/app.php):'xhprof' => ['enable' => true,'output_dir' => './runtime/xhprof',],public/index.php)中启动/结束分析:if (config('app.xhprof.enable')) {xhprof_enable(XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY);}// 请求处理完成后保存分析数据if (config('app.xhprof.enable')) {$data = xhprof_disable();$xhprof_runs = new XHProfRuns_Default();$run_id = $xhprof_runs->save_run($data, "thinkphp");echo "<a href='http://localhost:8000/?run=$run_id&source=thinkphp'>查看分析报告</a>";}composer require barryvdh/laravel-debugbar(兼容ThinkPHP);provider.php):$this->app->register(BarryvdhDebugbarServiceProvider::class);middleware.php):BarryvdhDebugbarMiddlewareDebugbarMiddleware::class,结合Ubuntu系统工具监控服务器资源(CPU、内存、磁盘、网络),判断是否因系统资源不足导致性能问题。
sudo apt install htop,实时查看CPU、内存使用率,排序进程占用。sudo apt install sysstat,监控系统整体性能(如进程、内存、IO、CPU):vmstat 1 5# 每1秒刷新一次,共5次sudo apt install sysstat,使用iostat查看磁盘读写情况:iostat -c -d 4# 每4秒刷新一次CPU和磁盘统计glances(sudo apt install glances)查看系统全面状态(CPU、内存、磁盘、网络、进程),支持远程监控。通过以上方法,可实现对ThinkPHP应用在Ubuntu环境下的全方位性能监控,从基础日志到代码级分析,再到系统资源排查,快速定位并解决性能问题。