Nginx 日志处理

1、 nginx日志统计独立ip的个数:
awk '{print $1}' /access.log | sort | uniq | wc -l
2、  查询访问最多的前10个ip awk '{print $1}' /access.log | sort | uniq -c | sort -nr | head -10 3、  查看某段时间的 grep "2012:0[3-6]" nginx.log | 4、  访问次数最多的IP netstat -ntu | tail -n +3 | awk '{ print $5}' | cut -d : -f 1 | sort | uniq -c| sort -n -r | head -n 5
注释:
  tail
-n +3   
  // 去掉前两行   awk
'{ print $5}'
  // 取数据的低5域(第5列)   cut -d: -f 1
  // 取IP部分。   sort
  // 对IP部分进行排序。   uniq
-c
  // 打印每一重复行出现的次数。(并去掉重复行)   sort
-n -r
  // 按照重复行出现的次序倒序排列。   head
-n 5
  //
取排在前5位的IP 5、  假设统计一天 access.log 日志每小时每IP访问次数 awk -vFS="[:]" '{gsub("-.*","",$1);num[$2" "$1]++}END{for(i in num)print i,num[i]}' logs/access.log

 

二、生产环境日志排查统计:

  1、  访问最多IP 排序

# cat show_log.sh
  // 执行  ./show_log.sh file.log

#!/bin/bash
if [ $# -eq 0 ]; then
echo "Eroor:please specify logfile."
exit 0
else
LOG=$1
fi


if [ ! -f $1 ]; then
echo "Sorry,not find this nginx file ,please tey again!"
exit 0
fi


#### 访问最多的IP #####
echo "Most of the ip:"
echo " ------------- "
awk '{print $1}' $LOG |sort |uniq -c |sort -nr |head -10
echo
echo


##### 产生时间段 #####
echo "Most of the time:"
echo " ------------- "
awk '{print $4}' $LOG | cut -c 14-18 |sort |uniq -c |sort -nr |head -10
echo
echo


##### 最多的页面 #######
echo "Most of the page:"
echo " ------------- "
# awk '{print $11}' $LOG |sed 's/^.* \(.cn* \)\''/\ 1/g' |sort |uniq -c |sort -nr |head -10
awk '{print $11}' $LOG |sed 's/^.*\(.cn*\)\"/\1/g' |sort |uniq -c |sort -nr |head -10
echo
echo

 

 三、日志分割

以天为单位进行分割示例:

加入Crontab 进行执行每小时执行

crontab -e
0
* * * * rm-log.sh >/dev/null 2>&1

注释:

  每五分钟执行 */5 * * * *
  每小时执行 0 * * * *
  每天执行 0 0 * * *
  每周执行 0 0 * * 0
  每月执行 0 0 1 * *
  每年执行 0 0 1 1 *

 

#!/bin/bash
#nginx
logs_path="/data/logs"
logs_dir=${log_path}/$(date -d"yesterday" +"%Y")/$(date -d "yesterday" +"%m")
logs_file=$(date -d "yesterday" +"%Y%m%d")
mkdir
-p /data/backuplogs/$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")
tar
-cf ${logs_path}/${logs_file}.tar.gz ${logs_path}*.log_path}/*.log rm -rf ${logs_path}/${logs_file}.tar.gz /data/backuplogs/${date -d "yesterday" +"%Y"}/$(date -d "yesterday" +"%m")
# // 重新启动nginx /etc/init.d/nginx restart # // 自动删除一个月前的打包日志文件; for oldfiles in 'find /data/backuplogs/$(date -d "30 day ago" +"%Y")/$(date -d "30 days ago "%m")/ -type f -mtime +30' do rm -f $oldfiles done

 

posted @ 2017-11-17 15:19  01234567  阅读(640)  评论(0编辑  收藏  举报