Promtail+Loki+Grafana采集nginx日志

1 部署Loki+Grafana

# 1、准备目录
mkdir evaluate-loki
cd evaluate-loki
# 2、下载默认配置文件
wget https://raw.githubusercontent.com/grafana/loki/main/examples/getting-started/loki-config.yaml -O loki-config.yaml
wget https://raw.githubusercontent.com/grafana/loki/main/examples/getting-started/alloy-local-config.yaml -O alloy-local-config.yaml
wget https://raw.githubusercontent.com/grafana/loki/main/examples/getting-started/docker-compose.yaml -O docker-compose.yaml

加入以下几行
cat loki-config.yaml
---
auth_enabled: false
server:
  http_listen_address: 0.0.0.0
  http_listen_port: 3100

docker-compose up -d

2 部署Promtail

curl -O -L "https://github.com/grafana/loki/releases/download/v2.7.4/promtail-linux-amd64.zip"

 cat restart-promtail.sh
#!/bin/bash
##############################################################
# File Name:restart-promtail.sh
# Version:V1.0
# Author: cmy

# Desc:
##############################################################
#!/bin/bash
echo "Begin stop promtail"
ps -ef | grep promtail-linux-amd64 | grep -v grep | awk '{print $2}' | xargs kill -9

echo "Begin start promtail...."
nohup ./promtail-linux-amd64 --config.file=promtail-local-config.yml > ./promtail-9080.log 2>&1 &


cat promtail-local-config.yml
server:
  http_listen_port: 9080
  grpc_listen_port: 0

positions:
  filename: /tmp/positions.yaml  # 确保目录可写

clients:
  - url: http://10.168.10.91:3100/loki/api/v1/push
    # 如果 Loki 启用了多租户认证(根据之前错误)
    external_labels:
      __tenant_id__: "fake"  # 与 Loki 的 X-Scope-OrgID 对应

scrape_configs:
- job_name: nginx
  static_configs:
  - targets: [localhost]
    labels:
      job: nginx  # 必须保留!这是 Loki 查询的主要标签
      host: namenode01
      env: production
      __path__: /var/log/nginx/access.log  # Nginx 默认访问日志路径
  pipeline_stages:
    - match:
        selector: '{job="nginx"}'
        stages:
        - regex:
            expression: '^(?P<ip>\S+) \S+ \S+ $$(?P<timestamp>[^$$]+)\] "(?P<method>\S+) (?P<path>\S+) HTTP/\d\.\d" (?P<status>\d+) (?P<bytes>\d+) "(?P<referer>[^"]*)" "(?P<user_agent>[^"]*)"'
        - timestamp:
            source: timestamp
            format: '02/Jan/2006:15:04:05 -0700'
        - labels:
            method:  # 将 method 提取为标签
            status: # 将 status 提取为标签
        - metrics:
            bytes_total:
              type: Counter
              description: "Total bytes served"
              source: bytes
              config:
                action: inc

./restart-promtail.sh

3 添加数据源并展示

3.1.1 添加 Loki 数据源

  1. 在左侧导航栏中选择 “Settings” -> “Data Sources”。
  2. 点击 “Add your first data source”。
  3. 选择 “Loki”。
  4. 配置 Loki 数据源的 URL(http://loki:3100)。
  5. 点击 “Save & Test”,确保数据源配置正确。

3.1.2 创建 Loki 数据源的 Dashboard

  1. 在左侧导航栏中选择 “+” -> “Dashboard”。
  2. 点击 “Add new panel”。
  3. 在 “Query” 中输入 Loki 查询语句,例如 '{job="nginx"}'
  4. 完成其他可视化配置,点击 “Apply”。

    #elk
上一篇
下一篇