需先执行composer require promphp/prometheus_client_php,再在脚本开头用require __dir__ . '/vendor/autoload.php';加载自动加载器;确保安装gmp扩展(php -m | grep gmp),缺失则报class not found;collectorregistry必须单例复用,避免每次请求重建;/metrics响应头须为content-type: text/plain; version=0.0.4,且逻辑轻量无io操作。

PHP 本身不提供 Prometheus 指标暴露能力,必须手动构造 /metrics 端点并确保它被 Prometheus 正确抓取;Grafana 只是展示层,不能跳过 Prometheus 直连 PHP。
怎么装 promphp/prometheus_client_php 并避免 Class not found
不是 composer require 之后就能直接用——漏掉 autoload 或扩展缺失是高频报错原因。
-
require __DIR__ . '/vendor/autoload.php';必须写在脚本最开头,路径别用./vendor/autoload.php(CLI 下易失效) - 检查是否装了依赖扩展:
php -m | grep -E 'gmp|apcu',缺gmp会直接 class not found,apcu缺失则需显式换存储后端 - 如果实在不能启 APCu,初始化时指定 NullStorage(仅测试):
new \Prometheus\CollectorRegistry(new \Prometheus\Storage\Null()) - 别在每次请求里 new
CollectorRegistry——它得单例复用,否则指标重置、counter 从 0 开始计
为什么 /metrics 返回空或 500,但 curl 能通
能访问不代表指标可采集。Prometheus 抓取失败常因响应格式或执行逻辑问题,和 HTTP 状态码无关。
- 响应头必须是
Content-Type: text/plain; version=0.0.4(不是charset=utf-8),否则 Prometheus 解析时报expected text format -
set_time_limit(5)要加在 metrics 路由开头,防止 DB 查询、缓存读取等拖慢抓取,触发默认 10s timeout - 别在
/metrics里调file_get_contents、curl或 ORM 查询——它必须轻量,只做指标序列化 - Nginx/Apache 要确认没把
/metrics当静态路径拦截,比如try_files $uri $uri/ /index.php?$query_string必须覆盖该路由
直方图 tp_api_response_time_seconds 没数据的真凶
不是没注册,而是 observe 调用时机或数值单位错了,或者 label 值含非法字符导致整条指标被丢弃。
-
$duration必须是秒级浮点数:ThinkPHP 的毫秒值要除以 1000,$histogram->observe($time_ms / 1000) - label 值不能含
/、?、=——用Request::rule()替代Request::url(),把/user/123归一为/user/{id} - buckets 必须显式设,别信默认值;API 场景推荐
[0.01, 0.05, 0.1, 0.25, 0.5, 1, 2],否则_sum和_count不配套,histogram_quantile()查不到结果 - HTTP 方法统一转大写:
strtoupper($request->method()),避免get和GET被当两个 label 维度
Grafana 面板查不到 PHP 指标?先盯住这三处
不是 Grafana 配错了,而是上游链路断在更早环节——90% 的“查不到”其实压根没进 Prometheus。
- 在 Prometheus Graph 页面输
php_app_http_requests_total,看有没有返回时间序列;没有就说明 scrape_configs 没生效,或 targets 地址写错(比如写了localhost但 Prometheus 在 Docker 里跑) - 检查 Prometheus status → Targets 页面,对应 job 状态是不是
UP;如果是DOWN,点进去看 Error,大概率是 DNS 不通、防火墙挡了、或 PHP 端口没监听 - Grafana 数据源选的是 Prometheus 实例,不是 PHP 地址;填错成
http://your-php-server/metrics就永远查不到——它只认已成功抓取的指标名
真正难调试的从来不是代码写法,而是跨进程状态(如 APCu key 冲突)、label 值的静默丢弃、以及 Prometheus 抓取超时与 PHP 执行超时的叠加效应——这些不会报错,只会让图表空着。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











