要使用 PHP 導出 Prometheus 格式的數據,您需要創建一個 PHP 腳本來收集和格式化性能指標
首先,確保您已安裝了 PHP。
創建一個名為 metrics.php
的新文件。在此文件中,我們將編寫收集和輸出指標的代碼。
在 metrics.php
文件中,添加以下代碼:
<?php
// 假設這是您的應用程序中的一些示例指標
$metric_requests_total = 100;
$metric_failed_requests_total = 5;
$metric_request_duration_seconds = 0.5;
// 定義指標并轉換為 Prometheus 格式
function format_metric($name, $value, $help = "", $type = "counter") {
echo "# HELP {$name} {$help}\n";
echo "# TYPE {$name} {$type}\n";
echo "{$name} {$value}\n";
}
// 輸出指標
header("Content-Type: text/plain");
format_metric("http_requests_total", $metric_requests_total, "Total number of HTTP requests.");
format_metric("failed_requests_total", $metric_failed_requests_total, "Total number of failed requests.", "gauge");
format_metric("request_duration_seconds", $metric_request_duration_seconds, "HTTP request duration in seconds.", "histogram");
php -S localhost:8000 metrics.php
curl
訪問 http://localhost:8000
,您應該看到類似以下內容的 Prometheus 格式的指標輸出:# HELP http_requests_total Total number of HTTP requests.
# TYPE http_requests_total counter
http_requests_total 100
# HELP failed_requests_total Total number of failed requests.
# TYPE failed_requests_total gauge
failed_requests_total 5
# HELP request_duration_seconds HTTP request duration in seconds.
# TYPE request_duration_seconds histogram
request_duration_seconds 0.5
注意:這只是一個簡單的示例,實際應用程序中的指標收集可能更復雜。您可能需要根據您的需求調整代碼。