跳至主要內容

Nginx日志信息采集

xw2022年3月8日大约 2 分钟NginxNginx

概述

access.log会记录相关信息,根据相关信息可统计很多数据,包括

解析

默认的配置解析文件格式为

#log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
#                  '$status $body_bytes_sent "$http_referer" '
#                  '"$http_user_agent" "$http_x_forwarded_for"';

案例如下:

220.196.160.73 - - [08/Aug/2022:16:21:29 +0800] "GET /static/css/chunk-vendors.e9e545fd.css HTTP/1.1" 200 7539 "https://file.yangliu97.top/" "Mozilla/5.0 (iPhone; CPU iPhone OS 13_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1 Mobile/15E148 Safari/604.1"

相关配置解释说明:

$remote_addr 对应的是真实日志里的220.196.160.73,即客户端的IP。

$remote_user 对应的是第二个中杠“-”,没有远程用户,所以用“-”填充。

[$time_local]对应的是[08/Aug/2022:16:21:29 +0800]。

“$request”对应的是"GET/static/css/chunk-vendors.e9e545fd.css "。

$status对应的是200状态码,200表示正常访问。

$body_bytes_sent对应的是7539字节,即响应body的大小。

## 这个可以用来做盗链判断,如果不是从指定域名访问不显示
$http_referer 对应的是"https://file.yangliu97.top/",若是直接打开域名浏览的时,referer就会没有值,为-。

$http_user_agent对应的是Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:56.0) Gecko/20100101 Firefox/56.0。

$http_x_forwarded_for 对应的是-或者空。

常见访问统计

awk '{print $1}' access.log | sort -n |uniq -c | sort -rn | head -n 100
cat access.log |awk '{print $7}'| sort|uniq -c| sort -rn| head -20 | more
grep '45.148.10.203' access.log |awk '{print $7}'|sort |uniq -c |sort -rn |head -n 100   
awk '{print $1}' access.log | sort -n |uniq -c |awk '{if($1 >100) print $0}'|sort -rn
awk '{print $7}' access.log | sort |uniq -c | sort -rn | head -n 100
grep -v ".php"  access.log | awk '{print $7}' | sort |uniq -c | sort -rn | head -n 100          
cat access.log | cut -d ' ' -f 7 | sort |uniq -c | awk '{if ($1 > 100) print $0}' | less
awk '{print $4}' access.log |cut -c 14-21|sort|uniq -c|sort -nr|head -n 100
awk '{print $4}' access.log |cut -c 14-18|sort|uniq -c|sort -nr|head -n 100
awk '{print $4}' access.log |cut -c 14-15|sort|uniq -c|sort -nr|head -n 100

性能分析

统计耗时接口, 列出传输时间超过 2 秒的接口,显示前5条

cat time_temp.log|awk '($NF > 2){print $7}'|sort -n|uniq -c|sort -nr|head -5