nginx简单的日志shell分析统计脚本
最近公司要求从nginx 的access日志中得到一些信息,方便日后判断分析
于是我自己写了一些nginx日志可以等到的信息需求如下:
简单的写了一个shell脚本,获取统计其中的参数。可能这个脚本需要优化的地方很多,只写了几点功能,先贴上,思路梳理
nginx日志参数简单介绍下
remote_addr:远端地址(客户端地址)
time_local:日志记录时间
request:请求地址和http协议
status:请求状态
body_bytes_sent 发送给客户端的字节数,不包括响应头的大小;
脚本为:
#!/bin/bash
#分析nginx日志,等到一些关键信息
#nginx日志格式
# log_format main '"$remote_addr" | "$time_local"| "$request" |'
# '"$status" | "$body_bytes_sent" | "$bytes_sent" |"$http_referer" |'
# '"$http_user_agent" | "$request_time" | "$upstream_addr"|"$upstream_response_time"|"$upstream_status" ';
#基本信息
nginx_log=/nginx/logs/access.log
tmp_analysis_log=/tmp/analysis.log
tomcat01=192.186.100.11:8080
tomcat02=192.168.100.12:8080
#获取前1分钟的时间格式
date_time=`date '+%d/%b/%Y:%k:%M' -d '-1 min'`
grep "$date_time" $nginx_log > $tmp_analysis_log
#统计
#总请求数
total_requests=`cat $tmp_analysis_log |wc -l`
#独立ip个数
ip_number_uniq=`cat $tmp_analysis_log | awk -F'|' '{print $1}'|uniq|wc -l`
#get请求个数
get_requerst_number=`cat $tmp_analysis_log |grep -w 'GET'|wc -l`
#post请求个数
post_requerst_number=`cat $tmp_analysis_log |grep -w 'POST'|wc -l`
#其他请求个数
other_requerst_number=`cat $tmp_analysis_log |grep -v -w 'POST'|grep -v -w 'GET'|wc -l`
#接口数
adasPlat_port_number=`cat $tmp_analysis_log |grep '/port/' |wc -l`
#负载到不同IP的次数
tomcat_ip_01=`cat $tmp_analysis_log |grep "$tomcat01" |wc -l`
tomcat_ip_02=`cat $tmp_analysis_log |grep "$tomcat02" |wc -l`
#tomcat后端统计
upstream_time_sum=0
upstream_time_max=0
upstream_time_min=1000000
byte_sent_sum=0
while read line;
do
upstream_time=`echo "$line" |awk -F'"' '{print $22}'`
#tomcat后端响应时长最大值,最小值寻找
if [[ $upstream_time > $upstream_time_max ]];then
upstream_time_max=$upstream_time
fi
if [[ $upstream_time < $upstream_time_min ]];then
upstream_time_min=$upstream_time
fi
#tomcat后端响应时长总时长
upstream_time_sum=$[${upstream_time_sum} + ${upstream_time}]
#总流量统计
byte_sent=`echo "$line" |awk -F'"' '{print $12}'`
byte_sent_sum=$[$byte_sent_sum + $byte_sent]
done < $tmp_analysis_log
byte_sent_sum02=`echo "scale=3;${byte_sent_sum}/1024" | bc |awk '{printf "%.3f",$0}'`
upstream_time_avg=`echo "scale=3;${upstream_time_sum}/${total_requests}" |bc |awk '{printf "%.3f",$0}'`
echo "总时长 $upstream_time_sum s"
echo "平均时长 $upstream_time_avg s"
echo "最小时长 $upstream_time_min s"
echo "最大时长 $upstream_time_max s"
echo "流量大小 $byte_sent_sum02 kb"