Nginx访问日志统计
2015 年 07 月 20 日
nginx

    生产中,我们需要Nginx访问日志,查一些需要的数据,这里作一些收集。

  • 假定配置nginx日志格式为

  • log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" $request_length $request_time $bytes_sent '
                      '"$upstream_cache_status"';
            
  • 响应码

  • 统计各种响应码数量并降序

  • cat access.log | cut -d '"' -f3 | cut -d ' ' -f2 | sort | uniq -c | sort -r
            
  • 查询某类响应码请求

  • awk '($9 ~ /504/)' access.log | awk '{print $7}' | sort | uniq -c | sort -r
            
  • URL

  • 某个URL访问量

  • awk '{print $7}' access.log | grep "/pay_success.html" | wc -l
            
  • 按URL请求量排序

  • awk '{print $7}' access.log | sort | uniq -c |sort -n -k 1 -r | more
            
  • GoAccess

  • 也可以使用GoAccess工具对nginx访问日志进行分析
  • 安装

  • sudo yum -y install geoip-devel ncurses ncurses-devel glib2-devel
    wget http://tar.goaccess.io/goaccess-0.9.2.tar.gz
    tar -xzvf goaccess-0.9.2.tar.gz
    cd goaccess-0.9.2/
    ./configure --enable-geoip --enable-utf8
    make && make install
            
  • 配置(文档可见这里)

  • vim /usr/local/etc/goaccess.conf
            
  • 分析日志文件

  • goaccess -f access.log
            
  • 生成分析报告

  • goaccess -f access.log -a > report.html
            
好人,一生平安。