You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Prometheus监控应用日志及实现日志超时未修改告警?

如何使用Prometheus监控应用程序的日志?

Prometheus本身不直接支持日志采集,通常需要搭配日志处理工具实现,以下是两种主流方案:

方案1:Loki + Promtail组合

  • 部署Promtail:在应用服务器上安装Promtail,配置它采集目标应用的日志文件并发送到Loki。
    示例Promtail配置片段:
    scrape_configs:
      - job_name: 'app-logs'
        static_configs:
          - targets: ['localhost']
            labels:
              job: 'my-app'
              __path__: '/var/log/my-app/*.log'
    
  • 部署Loki:作为日志存储系统接收Promtail的日志,提供与Prometheus兼容的查询接口。
  • Grafana关联:在Grafana中配置Loki数据源,实现日志的查询、可视化,还能结合Prometheus的指标做关联分析。

方案2:Fluentd + Prometheus Exporter组合

  • 部署Fluentd:配置Fluentd采集应用日志,过滤解析后将日志转换为Prometheus指标(如日志行数、错误日志计数)并暴露。
    示例Fluentd输出到Prometheus的配置片段:
    <match app.logs>
      @type prometheus
      <metric>
        name app_log_total
        type counter
        desc Total number of app logs
        label_keys ["level"]
      </metric>
    </match>
    
  • Prometheus采集配置:在prometheus.yml中添加job配置,采集Fluentd暴露的指标端点。

当应用日志文件距离当前时间超过300秒未被修改时,如何通过Prometheus触发邮件告警?

该需求需要结合node_exporter、Prometheus告警规则和Alertmanager实现:

步骤1:确保node_exporter采集文件系统指标

node_exporter默认会采集node_file_mtime_seconds指标(记录文件最后修改时间戳),确认你的node_exporter配置未禁用该采集项。

步骤2:配置Prometheus告警规则

创建告警规则文件(如log_inactive_rules.yml),添加以下规则:

groups:
- name: log_file_inactive_alerts
  rules:
  - alert: LogFileNotUpdated
    expr: time() - node_file_mtime_seconds{path="/var/log/my-app/app.log"} > 300
    for: 1m
    labels:
      severity: warning
    annotations:
      summary: "应用日志文件超过5分钟未更新"
      description: "日志文件 {{ $labels.path }} 最后修改时间距当前已超过300秒"

在Prometheus主配置文件中引入该规则:

rule_files:
  - "log_inactive_rules.yml"

步骤3:配置Alertmanager发送邮件告警

编辑Alertmanager配置文件(alertmanager.yml),添加邮件接收配置:

global:
  smtp_smarthost: 'smtp.example.com:587'
  smtp_from: 'prometheus-alerts@example.com'
  smtp_auth_username: 'prometheus-alerts@example.com'
  smtp_auth_password: 'your-smtp-password'
  smtp_require_tls: true

route:
  group_by: ['alertname']
  group_wait: 30s
  group_interval: 5m
  repeat_interval: 1h
  receiver: 'email-alert-group'

receivers:
- name: 'email-alert-group'
  email_configs:
  - to: 'admin@example.com'
    subject: 'Prometheus告警: {{ .CommonAnnotations.summary }}'
    html: '{{ .CommonAnnotations.description }}'

步骤4:验证配置

重启Prometheus和Alertmanager加载新配置,手动暂停应用日志写入,等待超过300秒后,检查Prometheus的Alerts页面是否触发告警,并确认邮件是否正常送达。

内容的提问来源于stack exchange,提问作者Andrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 02:22:14