熱門分類
載入中…
目錄0%

📊 Grafana + Loki + Promtail:打造 Linux Log 即時監控中心

    📊 Grafana + Loki + Promtail:打造 Linux Log 即時監控中心

    傳統使用 journalctltail -f 檢視日誌雖直覺,但缺乏搜尋、篩選與視覺化能力。 本文將帶你使用 Grafana + Loki + Promtail 建立完整的 Log Monitoring 堆疊, 實現 Linux 系統日誌的集中化收集、查詢與即時可視化儀表板。

    🧱 一、架構概覽

    整體資料流:

    [Promtail] → 收集 /var/log → 傳送至 [Loki]
    [Loki] → 儲存與索引 log 資料
    [Grafana] → 查詢 Loki 並顯示於儀表板
    
    • Promtail:Log Agent,用於蒐集系統日誌。
    • Loki:Log Database(類似 ELK 的 Logstash + ES)。
    • Grafana:視覺化與查詢介面。

    ⚙️ 二、安裝與環境設定

    1️⃣ 安裝 Grafana 與 Loki

    sudo apt update
    sudo apt install -y grafana loki promtail
    # 若套件庫無內建,可使用官方 repo:
    # https://grafana.com/docs/loki/latest/installation/
    

    2️⃣ 啟動服務

    sudo systemctl enable --now grafana-server
    sudo systemctl enable --now loki
    sudo systemctl enable --now promtail
    

    預設:

    • Grafana 介面 → http://localhost:3000 (預設帳密 admin/admin)
    • Loki API → http://localhost:3100

    📄 三、Promtail 設定檔

    Promtail 的配置定義了要收集哪些日誌與傳送目的地。

    # /etc/promtail/config.yml
    server:
      http_listen_port: 9080
      grpc_listen_port: 0
    
    positions:
      filename: /var/lib/promtail/positions.yaml
    
    clients:
      - url: http://localhost:3100/loki/api/v1/push
    
    scrape_configs:
      - job_name: system
        static_configs:
          - targets:
              - localhost
            labels:
              job: varlogs
              host: ${HOSTNAME}
              __path__: /var/log/*.log
    

    重新啟動以套用:

    sudo systemctl restart promtail

    🧩 四、Grafana 連接 Loki

    1. 登入 Grafana → 點選左側 ⚙️ → Data Sources
    2. 新增 Loki → URL 輸入 http://localhost:3100
    3. 儲存後即可查詢 Log。

    範例查詢:

    {job="varlogs"} |= "error"
    {host="web01"} |= "sshd"
    

    可快速篩選包含關鍵字的日誌行。

    📊 五、建立儀表板與警示

    1. 新增 Panel → 查詢 Source: Loki
    2. 輸入 LogQL,例如 {job="varlogs"} |~ "fail|error|denied"
    3. 選擇「Table」或「Time Series」顯示。
    4. 可設定警報條件:
      當 log 出現錯誤次數超過閾值 → 發送通知(Email、Webhook)。

    🛡 六、安全與效能建議

    • Promtail 採 positions.yaml 追蹤上次讀取位置,避免重複收集。
    • Loki 儲存建議使用 SSD,或搭配 filesystem chunks 模式。
    • Grafana 登入後立即修改預設密碼,並啟用 auth.basic

    🧭 七、行動清單(Checklist)

    ✅ 安裝並啟動 Grafana、Loki、Promtail
    ✅ 設定 Promtail 收集 /var/log/*.log
    ✅ 於 Grafana 新增 Loki 資料源
    ✅ 建立 dashboard 與 LogQL 查詢
    ✅ 設定警報或 Webhook 通知
    

    📘 結語

    相較傳統的 ELK Stack,Loki 以輕量級架構提供高效率的日誌索引。 透過 Grafana 進行整合,你可以快速檢視系統錯誤、效能瓶頸與安全事件。 對 Linux 維運人員而言,這是一套兼具速度與彈性的即時監控方案。


    🔗 延伸閱讀

    — WWFandy・監控實戰筆記

    🔗 分享這篇 LINE Facebook X

    沒有留言:

    字級