要在 PHP 中配置 Prometheus 告警,您需要遵循以下步骤:
安装 Prometheus:首先,您需要在服务器上安装 Prometheus。请参阅 Prometheus 官方文档中的安装指南。
安装 PHP 的 Prometheus 客户端库:为了从 PHP 应用程序收集指标并将其暴露给 Prometheus,您需要使用一个 PHP Prometheus 客户端库。一个流行的选择是 promphp/prometheus_client_php。要安装此库,请运行以下命令:
composer require promphp/prometheus_client_php
在 PHP 应用程序中集成 Prometheus 客户端库:在您的 PHP 代码中,使用 Prometheus 客户端库收集和暴露指标。例如,您可以创建一个简单的计数器来跟踪请求次数:
use Prometheus\CollectorRegistry;
use Prometheus\RenderTextFormat;
use Prometheus\Storage\InMemory;
use Prometheus\Storage\Redis;
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
use Psr\Http\Message\ServerRequestInterface;
$storage = new InMemory(); // 或者使用 Redis 存储,如果您的应用程序是分布式的
$registry = new CollectorRegistry($storage);
$counter = $registry->registerCounter('my_app', 'requests_total', 'Total number of requests');
$counter->inc();
// ... 处理请求 ...
$renderer = new RenderTextFormat();
$result = $renderer->render($registry->getMetricFamilySamples());
header('Content-Type: text/plain');
echo $result;
配置 Prometheus:创建一个名为 prometheus.yml 的配置文件,其中包含有关如何抓取您的 PHP 应用程序指标的信息。例如:
global:
  scrape_interval: 15s
scrape_configs:
  - job_name: 'my_php_app'
    static_configs:
      - targets: ['localhost:9091'] # 将此更改为您的 PHP 应用程序的实际地址和端口
确保将 targets 更改为您的 PHP 应用程序的实际地址和端口。
启动 Prometheus:使用以下命令启动 Prometheus,并指向您的配置文件:
prometheus --config.file=prometheus.yml
配置告警规则:在 Prometheus 中,您可以定义告警规则以在特定条件下触发通知。要配置告警规则,请在 Prometheus 配置文件(prometheus.yml)中添加一个 rule_files 部分,并创建一个包含告警规则的新文件。例如,在 prometheus.yml 中添加以下内容:
rule_files:
  - 'alerts.yml'
然后,创建一个名为 alerts.yml 的文件,其中包含您的告警规则。例如:
groups:
  - name: php_app_alerts
    rules:
      - alert: HighRequestRate
        expr: rate(my_app_requests_total[5m]) > 100
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "High request rate in PHP app"
          description: "The PHP app has received more than 100 requests per minute for the last 1 minute."
这将创建一个名为 “HighRequestRate” 的告警,当 PHP 应用程序在过去 5 分钟内每分钟收到超过 100 个请求时触发。
配置 Alertmanager:要接收告警通知,您需要设置一个 Alertmanager 实例。首先,请参阅 Alertmanager 官方文档中的安装指南。然后,创建一个名为 alertmanager.yml 的配置文件,其中包含有关如何发送通知的信息。例如:
global:
  resolve_timeout: 5m
route:
  group_by: ['alertname']
  group_wait: 10s
  group_interval: 5m
  repeat_interval: 3h
  receiver: 'email-notifier'
receivers:
  - name: 'email-notifier'
    email_configs:
      - to: 'your-email@example.com'
        from: 'alerts@example.com'
        smarthost: 'smtp.example.com:587'
        auth_username: 'your-smtp-username'
        auth_password: 'your-smtp-password'
        send_resolved: true
根据您的电子邮件提供商和 SMTP 服务器设置更改相应的值。
启动 Alertmanager:使用以下命令启动 Alertmanager,并指向您的配置文件:
alertmanager --config.file=alertmanager.yml
现在,当满足告警规则的条件时,您将收到有关 PHP 应用程序的电子邮件通知。请注意,这只是一个简单的示例,您可能需要根据您的需求调整配置。