You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计网站独立访客?基于Loki/Promtail/Grafana自部署环境

解决Nginx访问日志独立IP统计(Loki+Grafana)

问题核心

需要统计访问网站根路径(/或/index.html)的独立IP访客,生成持续增长的监控图表,之前的LQL查询因分组逻辑、过滤规则错误导致结果不符合预期。

正确查询步骤

1. 过滤目标请求并提取IP

如果Promtail未提前解析日志字段,先用正则提取访客IP并过滤根路径请求:

{filename="/var/log/nginx/akomercyjni.pl_access.log"} 
|= "GET / HTTP" or |= "GET /index.html HTTP"
| regexp `(?P<remote_ip>\d+\.\d+\.\d+\.\d+)`

如果已在Promtail中配置日志解析(推荐),直接用标签过滤更高效:

{filename="/var/log/nginx/akomercyjni.pl_access.log"} 
| request_uri="/" or request_uri="/index.html"

2. 生成持续增长的独立IP统计

要得到累计独立访客数,先按IP去重,再通过面板转换实现持续增长效果:

count by (remote_ip) (
  {filename="/var/log/nginx/akomercyjni.pl_access.log"} 
  |= "GET / HTTP" or |= "GET /index.html HTTP"
  | regexp `(?P<remote_ip>\d+\.\d+\.\d+\.\d+)`
)
  • 用Time Series面板:在「Transform」选项中选择Cumulative sum,即可生成持续上升的趋势曲线。
  • 只需显示当前累计总数:用Stat面板,直接展示查询结果的总和。

3. 之前查询的错误点

  • 初始查询用sum(count_over_time(...)) by (zdalneip),会按每个IP分组输出,因此出现多个子图表。需去掉by (zdalneip),改为先按IP去重再统计总数。
  • 简化后的查询未过滤根路径请求,也未对IP去重,统计的是所有请求数而非独立访客。

优化建议:Promtail提前解析日志

在Promtail配置中添加日志解析流水线,避免在Grafana中重复写正则:

scrape_configs:
- job_name: nginx
  static_configs:
  - targets: ['localhost']
    labels:
      job: nginx
      filename: /var/log/nginx/akomercyjni.pl_access.log
  pipeline_stages:
  - regex:
      expression: '^(?P<remote_ip>\d+\.\d+\.\d+\.\d+) - - \[(?P<timestamp>[^\]]+)\] "(?P<method>[A-Z]+) (?P<request_uri>[^"]+) HTTP/\d\.\d" (?P<status>\d+) (?P<body_bytes_sent>\d+) "(?P<referer>[^"]*)" "(?P<user_agent>[^"]*)"'
  - labels:
      remote_ip:
      request_uri:

配置后,查询可简化为:

count by (remote_ip) (
  {filename="/var/log/nginx/akomercyjni.pl_access.log", request_uri="/" or request_uri="/index.html"}
)

内容的提问来源于stack exchange,提问作者PomyloneKodowanie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 17:15:42