1、统计nginx的访问日志,统计访问总数,http状态码信息等
思路:先将access.log日志中的http状态码取出来,在我的nginx.conf配置下,access.log中一般awk ‘{print $9}’即为http状态码,但为了确保不会出现问题,首先采用grep精确匹配到格式为:HTTP/1.0或HTTP:/1.1 状态码,并用awk去除$2即为http状态码,最后通过wc命令统计。
方法一:
#!/bin/bash
reset_terminal=$(tput sgr0)
nginx_log_path='/usr/local/nginx/logs/access1.log'
#the log of nginx after filter
nginx_log_awkpath='/usr/local/nginx/logs/mynginx.log'
#filter log only with http code
cat ${nginx_log_path} | grep -ioE "HTTP\/1\.[1|0]\"[[:blank:]][0-9]{3}"| awk '{print $2}' > ${nginx_log_awkpath}
echoFun(){
echo -e '\E[32m' "$1" $reset_terminal $2
}
check_http_status(){
http_code_100=$(grep -o '1[0-9][0-9]' ${nginx_log_awkpath} | wc -l)
http_code_200=$(grep -o '2[0-9][0-9]' ${nginx_log_awkpath} | wc -l)
http_code_300=$(grep -o '3[0-9][0-9]' ${nginx_log_awkpath} | wc -l)
http_code_400=$(grep -o '4[0-9][0-9]' ${nginx_log_awkpath} | wc -l)
http_code_500=$(grep -o '5[0-9][0-9]' ${nginx_log_awkpath} | wc -l)
http_code_total=$(grep -o '[1-5][0-9][0-9]' ${nginx_log_awkpath} | wc -l)
echoFun "http status[100+]" "${http_code_100}"
echoFun "http status[200+]" "${http_code_200}"
echoFun "http status[300+]" "${http_code_300}"
echoFun "http status[400+]" "${http_code_400}"
echoFun "http status[500+]" "${http_code_500}"
echoFun "http status total" "${http_code_total}"
}
check_http_code(){
http_code_403=$(grep -o '403' ${nginx_log_awkpath} | wc -l)
http_code_404=$(grep -o '404' ${nginx_log_awkpath} | wc -l)
echoFun "http status[403]" "${http_code_403}"
echoFun "http status[404]" "${http_code_404}"
}
check_http_status
check_http_code
2、运行结果:
方法二:参考网上一些实现方法
实现方法类似,这里运用了awk判断来实现
#!/bin/bash
reset_terminal=$(tput sgr0)
nginx_log_path='/usr/local/nginx/logs/access1.log'
echoFun(){
echo -e '\E[32m' "$1" $reset_terminal $2
}
check_http_status(){
http_status_codes=(`cat ${nginx_log_path} | grep -ioE "HTTP\/1\.[1|0]\"[[:blank:]][0-9]{3}" | awk '{
if($2>=100 && $2<200)
{i++}
else if($2>=200 && $2<300)
{j++}
else if($2>=300 && $2<400)
{k++}
else if($2>=400 && $2<500)
{l++}
else if($2>=500)
{m++}
}END{
#判断 i存在输出i,否则输出0
print i?i:0,j?j:0,k?k:0,l?l:0,m?m:0,i+j+k+l+m
}'
`)
echoFun "http status[100+]" "${http_status_codes[0]}"
echoFun "http status[200+]" "${http_status_codes[1]}"
echoFun "http status[300+]" "${http_status_codes[2]}"
echoFun "http status[400+]" "${http_status_codes[3]}"
echoFun "http status[500+]" "${http_status_codes[4]}"
echoFun "http status total" "${http_status_codes[5]}"
}
check_http_code(){
http_code=(`cat ${nginx_log_path} | grep -ioE "HTTP\/1\.[1|0]\"[[:blank:]][0-9]{3}" | awk -v total=0 '{
if($2!="")
{code[$2]++;total++}
else
{exit}
}END{
print code[403]?code[403]:0,code[404]?code[404]:0,total
}'
`)
echoFun "http status[403]" "${http_code[0]}"
echoFun "http status[404]" "${http_code[1]}"
echoFun "http status tatal" "${http_code[2]}"
}
check_http_status
check_http_code
输出结果:
输出结果是一致的。
这些脚本还需要进行进一步的优化,例如用户可以针对某个时间点甚至是时间段内进行统计。