Linux Health Sentinel 第2阶段:从指标到含义,使用 Grafana Loki

发布: (2026年2月6日 GMT+8 01:17)
3 min read
原文: Dev.to

Source: Dev.to

概念:Metrics vs. Logs

Metrics 告诉你 有问题;logs 告诉你 问题是什么

架构

  • Loki(图书馆) – 在你的笔记本电脑上运行,存储日志并提供搜索功能。
  • Promtail(间谍) – 在 Vagrant 虚拟机上运行,实时读取日志文件并将其发送到 Loki。

先决条件

  • 已在 Ubuntu 笔记本上运行 Grafana + Prometheus。
  • 来自 Phase 1 的 Vagrant 虚拟机(或任意本地 VM)。
  • 主机与虚拟机之间的基本网络连通。

步骤 1:搭建库(Loki)

# Download and unzip Loki
wget https://github.com/grafana/loki/releases/latest/download/loki-linux-amd64.zip
sudo apt update && sudo apt install unzip -y
unzip loki-linux-amd64.zip
chmod +x loki-linux-amd64

# Download the default config file
wget https://raw.githubusercontent.com/grafana/loki/main/cmd/loki/loki-local-config.yaml

运行 Loki:

./loki-linux-amd64 -config.file=loki-local-config.yaml

注意:此设置仅用于本地学习,运行时不启用身份验证。请勿直接将 Loki 暴露到互联网。

步骤 2:部署间谍(Promtail)

安装 Promtail

curl -O -L "https://github.com/grafana/loki/releases/download/v3.5.9/promtail-linux-amd64.zip"
unzip promtail-linux-amd64.zip
chmod a+x promtail-linux-amd64

配置 Promtail

# Download the basic config file
wget https://raw.githubusercontent.com/grafana/loki/main/clients/cmd/promtail/promtail-local-config.yaml

编辑 promtail-local-config.yaml,将 client URL 替换为你笔记本的 IP 地址(使用 hostname -I 查看):

clients:
  - url: http://:3100/loki/api/v1/push

scrape_configs:
  - job_name: system
    static_configs:
      - targets:
          - localhost
        labels:
          job: varlogs
          host: vagrant-vm
          __path__: /var/log/*log

运行 Promtail:

./promtail-linux-amd64 -config.file=promtail-local-config.yaml

步骤 3:在 Grafana 中可视化

  1. 打开 Grafana(http://localhost:3000)。
  2. Add Data Source → 选择 Loki
    • 将 URL 设置为 http://localhost:3100
    • 点击 Save & Test
  3. 前往 Explore 选项卡(指南针图标)。
  4. 使用 Label Browser 选择 job="varlogs"host="vagrant-vm"
  5. 点击 Run Query

启用实时日志流

  • 点击 Grafana 界面右上角的 Live 按钮。
  • Auto‑Refresh 调整为 5 秒或 10 秒,以实现近实时更新。

生成测试日志

sudo logger "Sentinel Test: Can you hear me, Grafana?"
sudo logger "Hello Loki, this is a test"
sudo logger "Sentinel Alert: Testing log flow to Grafana"
sudo logger -p user.err "Simulating a critical system error"
sudo logger "Hello Loki, this is test-2."

结论

接下来:让 sentinel 在检测到故障时通过 Slack、Discord 或电子邮件发送通知,使用 Alerting 功能实现。

Back to Blog

相关文章

阅读更多 »