如何通过NGINX Prometheus Exporter统计单个URL请求数?
如何按单个URL统计NGINX请求数
默认的NGINX stub_status只能输出全局请求指标,没法按路径拆分。要得到你要的number_of_requests{path:/job1}这类带路径标签的指标,有两种可行方案,推荐用日志解析的方式,无需修改NGINX编译参数:
方案1:用NGINX自定义日志 + 日志转Prometheus指标工具
第一步:修改NGINX配置,添加带请求路径的日志
在NGINX的http全局块里定义一个包含请求URI的日志格式,然后在你的server块里启用这个日志:
http { # 保留你原有的http配置,新增下面的日志格式 log_format prometheus_log '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$request_uri"'; server { listen 8080 default_server; listen [::]:8080 default_server; # 新增这条,指定日志文件路径,自己按需修改 access_log /var/log/nginx/django_access.log prometheus_log; # 保留你原有的location配置 location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $http_host; proxy_redirect off; proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; } location /metrics { stub_status on; } } }
重启NGINX让配置生效。
第二步:用nginx-log-exporter解析日志生成指标
这个工具专门用来把NGINX日志转换成Prometheus可识别的指标。下载对应系统的二进制包后,创建一个配置文件(比如exporter-config.yaml):
listen: port: 9113 logs: - name: django_proxy path: /var/log/nginx/django_access.log format: "$remote_addr - $remote_user [$time_local] \"$request\" $status $body_bytes_sent \"$http_referer\" \"$http_user_agent\" \"$request_uri\"" labels: job: django_nginx metrics: - name: number_of_requests type: counter help: "Request count per specific path" path: "$request_uri" match: "^/(job1|job2)$" # 精准匹配/job1和/job2,要加其他路径直接在括号里追加 labels: path: "$request_uri"
启动工具:
./nginx-log-exporter -config.file=exporter-config.yaml
第三步:配置Prometheus抓取这个指标
在你的Prometheus配置文件里新增一个抓取任务:
scrape_configs: # 原有其他任务... - job_name: 'nginx_path_requests' static_configs: - targets: ['localhost:9113']
重启Prometheus后,就能在指标里看到number_of_requests{path="/job1"}和number_of_requests{path="/job2"}了。
方案2:用第三方NGINX模块(需重新编译NGINX)
如果不想依赖日志工具,可以编译NGINX时加入ngx_http_reqstat_module这个第三方模块,然后通过map匹配路径统计:
http { map $request_uri $path_tag { ~^/job1$ /job1; ~^/job2$ /job2; default /other; } req_status_zone path_zone $path_tag 10m; server { # 保留原有配置 req_status path_zone; location /path_metrics { req_status_show; } } }
之后用Prometheus exporter抓取/path_metrics的输出,再通过PromQL加工成你要的格式。但这个方法需要重新编译NGINX,适合有编译能力的场景,日常更推荐方案1。
内容的提问来源于stack exchange,提问作者stephen
相关产品推荐
相关产品推荐

