Linux环境下ThinkPHP性能监控方案
ThinkPHP提供内置日志模块,可记录请求、错误及性能相关信息,是基础监控手段。
application/config.php,设置日志类型为file(存储到runtime/log目录)、日志级别(info/debug/warn/error):'log' => [ 'type' => 'file', 'var_log_path' => './runtime/log', 'level' => ['info', 'debug', 'warn', 'error'], ], Log门面记录关键信息,如请求开始/结束、错误堆栈:\think\facade\Log::info('请求开始:' . request()->url()); \think\facade\Log::error('数据库查询失败:' . $e->getMessage()); 通过中间件捕获请求耗时、内存使用等指标,扩展基础日志功能。
app/middleware目录下新建PerformanceMiddleware.php,记录请求耗时:namespace app\middleware; use think\facade\Log; use think\middleware\BaseMiddleware; class PerformanceMiddleware extends BaseMiddleware { public function handle($request, \Closure $next) { $start_time = microtime(true); $response = $next($request); $cost_time = microtime(true) - $start_time; Log::info("请求【{$request->url()}】耗时:{$cost_time}秒,内存:".memory_get_peak_usage()/1024/1024."MB"); return $response; } } application/middleware.php中添加中间件,全局生效:return ['app\middleware\PerformanceMiddleware']; 适合需要自定义指标、可视化监控的场景,支持实时报警。
prometheus.yml添加ThinkPHP应用作为抓取目标(需应用暴露指标接口)。think-prometheus)收集请求次数、耗时、错误率等指标,暴露为HTTP接口(如/metrics)。ThinkPHP Grafana Dashboard),可视化展示性能趋势。提供全栈监控(应用、数据库、基础设施),支持ThinkPHP无缝集成,无需修改代码即可监控性能。
datadog.yaml开启PHP监控。composer require datadog/php-datadogstatsd app/provider.php中绑定Datadog客户端:namespace app; use think\Service; use DataDog\DogStatsd; class DatadogService extends Service { public function register() { $this->app->bind('datadog', function () { $config = config('datadog'); // 配置文件中定义Agent地址、命名空间等 return new DogStatsd($config); }); } } $datadog = app('datadog'); $datadog->timing('thinkphp.controller.index.time', microtime(true) - $start_time); $datadog->increment('thinkphp.controller.index.requests'); 专注于应用性能管理(APM),提供代码级性能分析、事务追踪、数据库查询分析等功能。
newrelic.so),设置应用名称、许可证密钥。通过系统自带工具监控ThinkPHP运行的基础环境,快速定位资源瓶颈。
ThinkPHP依赖MySQL等数据库,监控数据库性能是保障应用性能的关键。
slow_query_log=1),分析执行时间超过阈值的SQL语句,优化索引或查询逻辑。EXPLAIN分析执行计划,检查是否使用了索引、是否存在全表扫描。