shell脚本统计nginx访问日志access.log

核心代码:
先取出所有的状态码,再筛选1-5开头的状态码          
cat ${nginx_log_path} | grep -ioE "HTTP\/1\.[1|0]\"[[:blank:]][0-9]{3}"| awk '{print $2}' > ${nginx_log_awkpath}  

http_code_100=$(grep -o '1[0-9][0-9]' ${nginx_log_awkpath} | wc -l) 

法1:

#!/bin/bash
nginx_log_path='/usr/local/var/log/nginx//access.log'
nginx_log_awkpath='/usr/local/nginx/logs/mynginx.log'

cat ${nginx_log_path} | grep -ioE "HTTP\/1\.[1|0]\"[[:blank:]][0-9]{3}"| awk '{print $2}' > ${nginx_log_awkpath}

echoFun(){
        echo "\033[31m $1 \033[0m" $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_status

法2:

#!/bin/bash
nginx_log_path='/usr/local/var/log/nginx/access.log'

echoFun(){
        echo "\033[31m $1 \033[0m" $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{
        	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]}"
}
check_http_status

注意: linux命令行用 echo -e "\033[31m 文字内容 \033[0m" 标红文字内容,但是再shell脚本中,不需要-e,直接echo "\033[31m 文字内容 \033[0m" 

关于echo 不同颜色标亮文字的用法详见:http://blog.51cto.com/onlyzq/546459

格式如下:  echo -e "\033[字背景颜色;文字颜色m字符串\033[0m"


转自:https://blog.csdn.net/heshan307/article/details/52357411

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值