使用Loki promtail 收集Linux原生部署應用日志
在Kubernetes集群中部署Loki后,默認只能收集Kubernetes集群中的系統日志。然而,對于在Linux服務器上原生部署的業務系統,無法直接進行日志收集。這就導致了在日常業務交互中需要查詢這些系統的日志時存在困難。為了解決這個問題,我們計劃在Linux服務器上安裝Promtail來收集日志,并將其推送到Loki,以實現統一的日志分析和檢索。
Promtail是Loki的客戶端代理,它負責在Linux服務器上收集日志。通過在每個Linux服務器上安裝和配置Promtail,我們可以將業務系統的日志數據發送到Loki進行集中存儲和分析。
圖片
1. 前置依賴
- Loki 集群,如果不知如何按照,請參考:10分鐘在K8s中部署輕量級日志系統Loki
- Linux 服務器可以訪問Loki集群
2. 下載安裝 promtail
wget https://github.com/grafana/loki/releases/download/v2.7.3/promtail-linux-amd64.zip
3. 解壓并遷移文件至/usr/local/promtail文件夾下
unzip promtail-linux-amd64.zip
mkdir /usr/local/promtail
mv promtail-linux-amd64 /usr/local/promtail
4. 創建并修改配置文件
vi config.yaml
server:
http_listen_port: 9080
grpc_listen_port: 0
#讀取位置保存文件
positions:
filename: /opt/promtail/positions.yaml # This location needs to be writeable by Promtail.
## 指定推送Loki地址
clients:
- url: http://172.18.1.47:31300/loki/api/v1/push
scrape_configs:
- job_name: system
pipeline_stages:
#日志換行,匹配開頭
- multiline:
firstline: ^\d{1,2}:\d{2}:\d{2}.\d{1,3}
max_lines: 128
max_wait_time: 3s
#靜態配置
static_configs:
- targets:
- localhost
#定義靜態標簽
labels:
job: smartpark-agent # A `job` label is fairly standard in prometheus and useful for linking metrics and logs.
node_name: 172.17.1.55 # A `host` label will help identify logs from this machine vs others
app: smartpark-agent
__path__: /data/logs/*log # The path matching uses a third party library: https://github.com/bmatcuk/doublestar
3.編譯自啟動腳本
cat > /usr/lib/systemd/system/promtail.service <<EOF
[Unit]
Descriptinotallow=promtail
Documentatinotallow=https://github.com/grafana/loki/tree/master
After=network.target
[Service]
Type=simple
User=root
ExecStart=/usr/local/promtail/promtail-linux-amd64 -config.file=/usr/local/promtail/config.yaml
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
4.啟動命令
#啟動
systemctl start promtail
#查看狀態
systemctl status promtail
#設置開機啟動
systemctl enable promtail
圖片
5. 查看驗證
登錄Grafana在Explore 中選擇標簽 app = smartpark-agent, 可以查詢到相關日志,如下圖
圖片