1. 为什么要搭建日志监控系统?
在复杂的分布式系统和容器化应用中,日志是排查问题的重要工具。但传统的 grep + cat 方式已不适用于大规模日志管理。因此,Loki + Promtail + Grafana 这一组合成为了一种高效、低成本的日志监控方案。
o Loki:类似 Prometheus 的日志系统,支持多种数据存储后端。
o Promtail:日志收集代理,负责从服务器采集日志并推送到 Loki。
o Grafana:可视化日志数据,支持实时查询和分析。
2. Loki 监控架构
[应用程序日志] -> [Promtail] -> [Loki] -> [Grafana]
o Promtail 负责采集日志,类似于 Filebeat。
o Loki 作为集中式日志存储,支持分布式架构。
o Grafana 负责展示日志,并结合监控数据进行分析。
3. Loki + Promtail + Grafana 安装与配置
3.1 安装 Loki
在 Linux 服务器上执行:
wget https://github.com/grafana/loki/releases/latest/download/loki-linux-amd64.zip
unzip loki-linux-amd64.zip
chmod +x loki-linux-amd64
编辑 loki-config.yml:
auth_enabled: false
server:
http_listen_port: 3100
ingester:
lifecycler:
ring:
kvstore:
store: inmemory
schema_config:
configs:
- from: 2024-01-01
store: boltdb-shipper
object_store: filesystem
schema: v11
index:
prefix: index_
period: 24h
运行 Loki:
./loki-linux-amd64 --config.file=loki-config.yml &
3.2 安装 Promtail
下载并安装:
wget https://github.com/grafana/loki/releases/latest/download/promtail-linux-amd64.zip
unzip promtail-linux-amd64.zip
chmod +x promtail-linux-amd64
编辑 promtail-config.yml:
server:
http_listen_port: 9080
positions:
filename: /var/lib/promtail/positions.yaml
clients:
- url: http://localhost:3100/loki/api/v1/push
scrape_configs:
- job_name: "varlogs"
static_configs:
- targets:
- localhost
labels:
job: "varlogs"
__path__: /var/log/*.log
启动 Promtail:
./promtail-linux-amd64 --config.file=promtail-config.yml &
4. 配置 Grafana 进行日志查询
1. 访问 http://localhost:3000,默认用户名密码为 admin/admin。
2. 在 Data Sources 添加 Loki,地址填 http://localhost:3100。
3. 进入 Explore 选项,选择 Loki 数据源,输入查询:
{job="varlogs"} | json | line_format "{{ .msg }}"
4. 配置告警规则,当出现 ERROR 级别日志时触发通知。
5. 总结
o Loki + Promtail 让日志管理变得轻量级且高效。
o 结合 Grafana,不仅能查询日志,还能实现告警通知。
o 适用于 Kubernetes、Docker、微服务等场景,特别适合 DevOps 团队使用。
这套日志监控系统轻量、易扩展,非常适合作为 ELK(Elasticsearch + Logstash + Kibana) 的替代方案。
你是否已经在使用 Loki?欢迎评论区讨论!