Torres-tao  

日志分析

nginx一般默认日志路径为:nginx的安装路径下面的logs目录

root@aliyun nginx]# pwd
/usr/local/nginx
[root@aliyun nginx]# cd logs/
[root@aliyun logs]# ls
access.log  error.log  nginx.pid

nginx日志的格式一般在nginx.conf里面配置,常见的格式配置如下:

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
access_log  logs/access.log  main;

PS:

$remote_addr, $http_x_forwarded_for 记录客户端IP地址
$remote_user 记录客户端用户名称
$request 记录请求的URL和HTTP协议
$status 记录请求状态
$body_bytes_sent 发送给客户端的字节数,不包括响应头的大小; 该变量与Apache模块mod_log_config里的“%B”参数兼容。
$bytes_sent 发送给客户端的总字节数。
$connection_requests 当前通过一个连接获得的请求数量。
$http_referer 记录从哪个页面链接访问过来的
$http_user_agent 记录客户端浏览器相关信息
$request_length 请求的长度(包括请求行,请求头和请求正文)。
$request_time 请求处理时间,单位为秒,精度毫秒; 从读入客户端的第一个字节开始,直到把最后一个字符发送给客户端后进行日志写入为止。

一般分析Nginx日志有如下几点:

#分析截止目前位置访问量最高的IP排行
[root@aliyun ~]# awk '{print $1}' /usr/local/nginx/logs/access.log | sort | uniq -c | sort -nr | head -n 20
      9 89.32.41.122
      6 153.92.221.47
      4 8.142.112.1
      3 167.94.145.60
      3 167.94.138.47
      3 106.75.211.195
      2 64.227.3.78
      2 52.139.152.4
      2 47.101.140.62
      2 45.61.188.169
      2 34.73.105.94
      2 194.165.16.10
      2 192.3.118.129
      2 171.67.71.80
      2 109.237.103.9
      1 96.44.142.254
      1 92.118.160.9
      1 89.248.165.95
      1 80.94.93.125
      1 77.222.102.0
#找到当前日志中404或502错误的页面并统计
[root@aliyun ~]# awk '{print $0}' /usr/local/nginx/logs/access.log | egrep "404|502" | awk '{print 1,7,$9}' | more
1 7 404
1 7 404
1 7 404
1 7 404
1 7 404
1 7 405
1 7 404
1 7 404
1 7 405
1 7 404
1 7 404
1 7 404
1 7 404
1 7 404
1 7 404
1 7 405
1 7 404
1 7 404
1 7 404
1 7 404

日志切割

Nginx是一个非常轻量的Web服务器,具备体积小,性能高、速度快等诸多优点。但不足的是,比如产生的访问日志文件一直都是一个,不会自动地进行切割,如果访问量很大的话,将会导致日志文件非常大,不便于管理。故而编写以下脚本,进行定时切割日志

#!/bin/bash

#auto mv nginx log

set -x

server_log=/usr/local/nginx/logs/access.log
backup_log_dir=/data/backup/$(date +%Y%m%d)

echo -e "\033[32mPlease wait start cut shell scripts...\033[1m"
sleep 3
if [ ! -d ${backup_log_dir} ];then
    mkdir -p ${backup_log_dir}
fi

mv $server_log $backup_log_dir

kill -USR1 $(cat /usr/local/nginx/logs/nginx.pid)

echo "--------------------------------------"
echo "The Nginx log Cutting Successfully!"
echo "You can access backup nginx log ${backup_log_dir}/access.log files."

最后,在crontab中添加定时任务,每晚自动去切割日志

0 0 * * * /bin/sh /data/sh/auto_nginx_log.sh >> /tmp/nginx_cut.log 2>&1
posted on 2022-05-11 15:27  雷子锅  阅读(94)  评论(0编辑  收藏  举报