PHP应用监控:高级指标与告警

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

引言:为什么基础监控不够用?

PHP应用的基础监控(“存活/死亡”检查和CPU负载)在高负载下会失效。当您的应用每秒处理数千个请求时,标准指标无法显示瓶颈:慢速数据库查询、长时间进程中的内存泄漏或突发的延迟峰值。

在本文中,我们将探讨高级监控:采集业务指标、实时性能分析、基于百分位的告警配置以及与现代化可观测性技术栈(Prometheus + Grafana)的集成。您将学习如何部署工具,不仅能看到应用“宕机”,还能在问题发生前进行预测。



1. 高级指标:从HTTP状态码到业务指标

标准计数器(请求数量、200/500状态码)只是基础。要进行深入分析,需要采集:

  • 延迟: p50、p95、p99响应时间。p99的异常表明工作中有“异常值”。
  • 内存消耗: 不仅是峰值,还包括单个请求内的增长速度。
  • 外部调用执行时间: Redis、MySQL、RabbitMQ——每个服务都应有自己的指标。
  • 业务指标: 已完成的订单数量、验证错误数、队列处理速度。

使用 promphp/prometheus_client_php 采集指标的示例:

use Prometheus\\CollectorRegistry;use Prometheus\\RenderTextFormat;use Prometheus\\Storage\\InMemory;

$registry = new CollectorRegistry(new InMemory());

// 请求执行时间的直方图$histogram = $registry->registerHistogram( 'app', 'request_duration_seconds', 'HTTP request duration', ['method', 'endpoint'], [0.1, 0.5, 1.0, 2.0, 5.0]);

// 业务事件计数器$counter = $registry->registerCounter( 'business', 'orders_total', 'Total orders created', ['status'] // success/failed);

// 在中间件中测量时间$start = microtime(true);// ... 执行请求 ...$duration = microtime(true) - $start;$histogram->observe($duration, ['GET', '/api/orders']);


2. 健康检查与深度探测:验证依赖项

简单的 ping 端点无法检查数据库、缓存或队列的可用性。创建一个模拟真实请求的综合健康检查:

// health.php$checks = [    'database' => function () {        $db = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');        $db->query('SELECT 1');        return true;    },    'redis' => function () {        $redis = new Redis();        $redis->connect('127.0.0.1', 6379);        $redis->ping();        return true;    },    'queue' => function () {        // 检查 RabbitMQ 是否未溢出        $channel = new AMQPChannel(new AMQPConnection());        $queue = new AMQPQueue($channel);        return $queue->declareQueue() !== false;    }];

$results = [];$healthy = true;foreach ($checks as $name => $check) { try { $check(); $results[$name] = 'ok'; } catch (\\Throwable $e) { $results[$name] = 'failed: ' . $e->getMessage(); $healthy = false; }}

header('Content-Type: application/json');http_response_code($healthy ? 200 : 503);echo json_encode(['status' => $healthy ? 'healthy' : 'unhealthy', 'checks' => $results]);

这样的端点可以连接到Kubernetes的liveness/readiness探针,或外部监控服务(例如UptimeRobot),不仅检查可用性,还检查所有依赖项的健康状况。



3. 基于百分位和异常的告警

基于“平均响应时间”的告警常常会遗漏

博客

书籍推荐