Linux环境下ThinkPHP性能监控方案
通过ThinkPHP中间件机制,在请求处理前后记录时间差,获取请求响应时间(核心性能指标之一)。
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); // 执行请求 $end_time = microtime(true); // 记录结束时间 $cost_time = $end_time - $start_time; // 计算耗时 Log::info("请求路径:{$request->path()},耗时:{$cost_time}秒"); // 写入日志 return $response; } } (2)注册中间件:在application/middleware.php中添加中间件路径:return ['app\middleware\PerformanceMiddleware']; 借助成熟工具实现全面的性能监控(包括请求耗时、错误追踪、数据库查询等),支持可视化与报警。
composer require datadog/php-datadogstatsd;config/datadog.php,设置Agent地址、应用名称及标签:return [ 'host' => 'localhost', 'port' => 8125, 'namespace' => 'my_app', 'tags' => ['env:production'] ]; (3)创建服务提供者:在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'); return new DogStatsd($config); }); } } (4)使用监控:在控制器中调用timing方法记录指标(如请求耗时、数据库查询时间):namespace app\controller; use think\Controller; class Index extends Controller { public function index() { $datadog = app('datadog'); $start_time = microtime(true); // 业务逻辑... $elapsed_time = microtime(true) - $start_time; $datadog->timing('my_app.index_execution_time', $elapsed_time); // 记录执行时间 return 'Hello, ThinkPHP!'; } } think-prometheus)记录指标(如请求数、错误数);通过Linux自带工具监控服务器资源使用情况,间接反映ThinkPHP应用性能瓶颈。
top:实时查看CPU、内存占用,按M排序内存使用,按P排序CPU使用;vmstat 1:每秒输出系统整体状态(进程、内存、IO、CPU),关注r(运行队列长度)、free(空闲内存)、si/so(交换分区使用);iostat -x 1:监控磁盘IO(%util表示磁盘利用率,await表示平均IO等待时间);netstat -tulnp:查看网络连接状态(ESTABLISHED连接数、端口监听情况);sar -u 1 3:查看CPU历史使用率(1秒采样,共3次)。通过ThinkPHP内置日志功能记录错误与慢操作,结合ELK(Elasticsearch+Logstash+Kibana)等工具实现日志集中管理与分析。
config.php中设置日志级别(建议生产环境开启error、warn)与存储路径:'log' => [ 'type' => 'file', 'var_log_path' => './runtime/log', 'level' => ['error', 'warn'], ], try-catch捕获异常并写入日志:try { // 业务逻辑(如数据库查询、API调用) } catch (\Exception $e) { \think\facade\Log::error('捕获到异常:' . $e->getMessage() . ',文件:' . $e->getFile() . ',行号:' . $e->getLine()); return json(['status' => 500, 'msg' => '服务器内部错误']); } 结合监控结果实施针对性优化,提升ThinkPHP应用性能。
config.php中cache_on设为true,指定cache_path)、模板缓存(template_cache设为true)、数据库查询缓存(db_cache设为true);http.conf中AddOutputFilterByType DEFLATE text/html)、设置HTTP缓存头(Expires、Cache-Control)、使用负载均衡(如Nginx反向代理)分散请求压力。