Hyperf默认不暴露Prometheus指标,访问/metrics返回404,因hyperf/metric仅负责采集、需配合hyperf/prometheus组件通过Router::get('/metrics', [Handler::class, 'handle'])显式注册路由,并在metric.php中将driver设为Prometheus\Driver类。

Hyperf 默认不暴露 Prometheus 格式指标,直接启动后访问 /metrics 会 404 —— 因为 hyperf/metric 组件本身不自带 HTTP 暴露能力,必须手动集成 hyperf/prometheus 并配置路由和中间件。
确认已安装 metric 和 prometheus 扩展
两个包缺一不可:hyperf/metric 负责采集指标(如请求耗时、QPS、内存使用),hyperf/prometheus 负责将其序列化为 Prometheus 可抓取的文本格式并提供 HTTP 接口。
执行以下命令安装:
composer require hyperf/metric hyperf/prometheus
注意:hyperf/prometheus 依赖 promphp/prometheus_client_php,安装时会自动拉取;若因网络问题失败,可手动加镜像源或指定版本。
- Hyperf v3.x 推荐用
hyperf/prometheus ^3.1,避免与promphpv3.x 的接口不兼容 - 不要只装
hyperf/metric就以为能出指标 —— 它默认只往内存/Redis 写,不暴露 HTTP - 检查
config/autoload/metric.php是否存在,不存在则运行php bin/hyperf.php vendor:publish hyperf/metric
启用 Prometheus HTTP 指标端点
Hyperf 不像 Laravel 或 Gin 那样开箱即用,需要显式注册路由 + 中间件 + 配置驱动。
在 config/autoload/routes.php 中添加:
Router::get('/metrics', [\Hyperf\Prometheus\Handler::class, 'handle']);同时确保 config/autoload/metric.php 中的 driver 设置为 prometheus:
'driver' => \Hyperf\Metric\Adapter\Prometheus\Driver::class,
否则即使路由通了,也会返回空内容或报错 Driver not found。
- 该路由必须是 GET,且路径严格为
/metrics(Prometheus 抓取默认路径) - 如果用了自定义 Server(如 Swoole 配置了
http名称),需确认该 Server 已启用并监听对应端口 - 若部署在 Nginx 后,注意转发时不要 strip 掉
/metrics路径
验证指标是否正常输出
启动服务后,直接 curl 查看原始输出:
curl http://127.0.0.1:9501/metrics
应看到类似 Prometheus 文本格式的内容,例如:
# HELP http_server_requests_total The total number of HTTP requests
# TYPE http_server_requests_total counter
http_server_requests_total{method="GET",uri="/",status_code="200"} 12常见异常情况:
- 返回空或 404:检查路由是否注册成功、Server 是否运行、
hyperf/prometheus是否已加载 - 返回
Driver not found:确认metric.php中driver指向的是Prometheus\Driver类,不是MemoryDriver - 指标值全为 0 或长期不变:可能是中间件未生效,检查
config/autoload/middlewares.php是否启用了Hyperf\Metric\Middleware\MetricMiddleware
对接 Prometheus Server 抓取
Prometheus 配置文件 prometheus.yml 中添加 job:
scrape_configs:
- job_name: 'hyperf-app'
static_configs:
- targets: ['host.docker.internal:9501'] # 注意:Docker 容器内需用 host.docker.internal
关键点:
- 目标地址必须能被 Prometheus 进程网络访问到 —— 宿主机启动 Hyperf 时用
127.0.0.1:9501;Docker Compose 场景下不能写localhost,要用host.docker.internal或服务名 - Hyperf 默认监听
0.0.0.0:9501,但若配置了swoole.server.mode = 3(Task Worker 模式),需确保 metrics 收集逻辑仍在主 Worker 中执行(默认是的) - 如需自定义指标(如 DB 查询次数),调用
$this->counter->with(['type' => 'mysql'])->add(1)即可,无需额外注册 —— Prometheus Driver 会自动归类到hyperf_metric_counter下
指标命名会被自动加上 hyperf_ 前缀,比如你定义的 counter 名叫 db_query_count,最终在 Prometheus 中显示为 hyperf_db_query_count_total —— 这个前缀无法关闭,硬编码在 Prometheus\Driver 里。


















