ThinkPHP 5.1 可通过原生 PHP + cURL 轻量对接 Pushgateway 上报指标,需在业务逻辑末尾构造符合 Prometheus 文本协议的指标文本并 POST 到指定 URL,配合 honor_labels: true 的 Prometheus 抓取配置及 Pushgateway 持久化部署实现可观测性。

ThinkPHP 5.1 本身不内置 Prometheus 客户端,但完全可以通过轻量方式对接 Pushgateway 实现指标上报——核心不是框架支持,而是你在关键执行点主动构造并推送符合规范的指标文本。
在 ThinkPHP 5.1 中构造并推送指标
无需引入大型 SDK,用原生 PHP + cURL 即可完成。关键是在业务逻辑结束处(如命令行任务、定时脚本、控制器操作末尾)生成指标并推送。
- 使用
curl_init()或更简洁的file_get_contents()发起 POST 请求,目标为http://pushgateway-host:9091/metrics/job/{job_name}/instance/{instance_id} -
job_name建议按模块或任务命名,例如tp_user_sync、tp_order_cleanup,便于后续按 job 过滤和清理 -
instance_id可用$_SERVER['SERVER_NAME']或自定义标识(如app-prod-01),避免所有实例指标混在一起 - 推送内容为纯文本,格式严格遵循 Prometheus 文本协议,例如:
script_execution_status{env="prod",module="order"} 1<br> script_execution_duration_seconds{env="prod",module="order"} 8.42<br> script_processed_items_total{env="prod",module="order"} 1247
封装一个通用上报方法
在 application/common.php 或独立工具类中添加:
function pushToPushgateway($job, $metrics, $instance = null) {
$instance = $instance ?: ($_SERVER['SERVER_NAME'] ?? 'unknown');
$url = "http://pushgateway.example.com:9091/metrics/job/{$job}/instance/{$instance}";
$payload = implode("\n", $metrics) . "\n";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: text/plain']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
curl_close($ch);
return $res !== false;
}调用示例(在命令行任务 application/command/OrderSync.php 的 execute() 末尾):
通过Gate-Info和Gate-News MCP进行宏观驱动的加密货币分析,用于CPI、NFP、美联储、利率、工资等宏观因素与加密货币、日历或指标的关联。
立即学习“PHP免费学习笔记(深入)”;
- 记录开始时间:
$start = microtime(true); - 执行主逻辑(含异常捕获)
- 构造指标数组:
$metrics = [ "script_execution_status{env=\"prod\",module=\"order\"} " . ($success ? 1 : 0), "script_execution_duration_seconds{env=\"prod\",module=\"order\"} " . round(microtime(true) - $start, 3) ]; - 上报:
pushToPushgateway('tp_order_sync', $metrics);
Prometheus 配置要点
确保 Prometheus 能正确识别你推送的标签,而不是覆盖掉:
- 在
prometheus.yml的scrape_configs中,Pushgateway 抓取项必须启用honor_labels: true - job 名称建议单独设为
pushgateway-backup或pushgateway-tp,避免与其它 job 混淆 - 示例配置片段:
- job_name: 'pushgateway-tp'<br> honor_labels: true<br> static_configs:<br> - targets: ['pushgateway.example.com:9091']
运维与可观测性增强
光上报不够,还需保障长期可用和排查效率:
- Pushgateway 必须开启持久化(启动参数加
--persistence.file=/data/pushgateway.data),否则服务重启后所有指标丢失 - 为每个 job 单独推送,方便后期清理:可通过定时任务调用
DELETE /metrics/job/{job_name}清理过期数据(例如保留最近 3 天) - 在指标中加入版本号或 commit hash(如
script_version{"v":"v2.3.1"}),便于追踪不同发布版本的行为差异 - 失败时不要静默跳过,建议记录到日志并触发简单告警(如通过邮件或企业微信 webhook)


















