直接在 Nginx log_format 中引用 $request_method 并配合日志分析工具可按 HTTP 方法统计接口调用频次;需先定义含该变量的日志格式,再启用并用 awk、GoAccess、ELK 等工具进行分类、聚合或可视化分析。
直接在 Nginx 的 log_format 中引用 $request_method,再配合日志分析工具(如 awk、grep、goaccess 或 ELK),就能按 HTTP 方法分类统计接口调用频次。
在 http 块中定义一个包含 $request_method 的日志格式:
log_format method_log '$remote_addr - $remote_user [$time_local] ' '"$request_method $request_uri $http_version" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';
然后在 server 或 location 块中启用该格式:
access_log /var/log/nginx/api_access.log method_log;
假设日志路径为 /var/log/nginx/api_access.log,运行以下命令可统计 GET/POST/OPTIONS 等方法的总调用次数:
awk '{print $4}' /var/log/nginx/api_access.log | sort | uniq -c | sort -nrawk '$4 ~ /^(GET|POST|OPTIONS)$/ {print $4}' ... | sort | uniq -c
method_log 中 "$request_method 所在字段(引号内第一个词),实际位置取决于你的 log_format 字段分隔方式;可用 head -1 api_access.log | cut -d' ' -f4 确认结合 $time_local 可做更细粒度分析。例如提取「小时 + 方法」组合计数:
awk '{gsub(/[|:/," ",$3); print substr($3,1,2) " " $4}' /var/log/nginx/api_access.log | sort | uniq -c1234 08 POST,表示 8 点钟有 1234 次 POST 请求awk '$7 ~ /^/api/user/ && $4 == "POST" {print substr($3,1,2)}' ...
单靠文本日志适合临时排查,长期监控建议对接标准工具:
--log-format 和 --date-format,界面直接筛选 method 维度$request_method 映射为 keyword 字段,Kibana 中建 Terms 聚合图表collections.Counter 读取日志行,按 method 分组并写入 CSV,供 Excel 或 Grafana 展示