公司没有日志采集平台,又不太可能在业务系统里面搞事情。好在之前有玩过elk日志分析组合。直接从服务器上面撸出日志简单的用linux命令分析下吧。
Ngxin 日志格式化
- Nginx提供的访问日志里就蕴藏着大量有用信息。今天这篇要说的就是如果修改Nginx默认日志格式,以便于我们更好的挖掘有效指标。
编辑/etc/nginx.conf配置文件,在日志部分添加下面两段代码,编辑完成后重启Nginx服务即可。
log_format main '$host - $remote_addr - [$time_local] "$request" '
'$status $upstream_response_time $request_time "$http_referer"'
'"$http_user_agent" "$http_x_forwarded_for" $body_bytes_sent ';
access_log /var/log/nginx/access.log main;
简单罗列一下变量的含义:
$host访问域名$remote_addr客户端IP地址$time_local访问时间$status访问状态码$upstream_response_time应用返回到Nginx的时间$request_time请求时间$http_referer请求来源$http_user_agent访问客户端$http_x_forwarded_for客户端IP地址$body_bytes_sent返回给客户端大小
在server中不生效的问题
- 在server中增加
access_log /var/log/nginx/access.log main;
日期显示问题
[01/Jul/2020:03:25:17 +0800]官方默认是这种修改默认格式
log_format main '$host - $remote_addr - [$time_iso8601] "$request" '
'$status $upstream_response_time $request_time "$http_referer"'
'"$http_user_agent" "$http_x_forwarded_for" $body_bytes_sent ';
access_log /var/log/nginx/access.log main;
- 在server中增加下面代码
server {
if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})") {
set $year $1;
set $month $2;
set $day $3;
set $hour $4;
set $minutes $5;
set $seconds $6;
}
}
Nginx日志统计
(日志文件叫access.log 在当前目录下)
统计 PV,就是日志行数
cat access.log |wc -l
UV, 即是统计 IP 数
cat access.log |awk '{print $1}' |sort |uniq -c |wc -l
使用linux grep 进行统计
grep -E "POST|GET" access.log | awk -F '"' '{print $2,$3}' | awk '{print $2}'| sort | uniq -c | sort -k1nr | head -100
耗时的请求发生时间、所请求的 URI 和耗时
cat access.log | awk '{print $4,$7,$10,$NF}' | sort -k3 -nr | head -100
统计nginx访问频次最高的100个Ip**
grep -E "POST|GET" access.log | awk -F '"' '{print $(NF-1)}' | sort | uniq -c | sort -k1nr | head -100
统计nginx访问不正常(状态码400+)的前100个url和频次
grep -E "POST|GET" access.log | awk -F '"' '{print $2,$3}' | awk '{if ($4>="400") {print $4,$1,$2}}' | sort | uniq -c | sort -k1nr | head -100
统计nginx访问状态码非200的前100个url**和频次****
grep -E "POST|GET" access.log | awk -F '"' '{print $2,$3}' | awk '{if ($4!=200) {print $4,$1,$2}}' | sort | uniq -c | sort -k1nr | head -100
不同 URI 的平均耗时
grep -E "POST|GET" access.log | awk '{s[$10] += $NF;c[$10]++}END{for(i in s){print i,s[i]/c[i]}}' |sort -k2 -nr | head
每秒请求量统计
统计每秒的请求数,top100的时间点(精确到秒)
grep -E "POST|GET" access.log | awk '{print $4}' access.log |cut -c 14-21|sort|uniq -c|sort -nr|head -n 100
每分钟请求量统计
统计每分钟的请求数,top100的时间点(精确到分钟)
grep -E "POST|GET" access.log | awk '{print $4}' access.log |cut -c 14-18|sort|uniq -c|sort -nr|head -n 100
每小时请求量统计
统计每小时的请求数,top100的时间点(精确到小时)
grep -E "POST|GET" access.log | awk '{print $4}' access.log |cut -c 14-15|sort|uniq -c|sort -nr|head -n 100
统计蜘蛛抓取次数
grep 'Baiduspider' access.log |wc -l