nginx日志自定义和统计处理

发布于:2024-04-24 ⋅ 阅读:(19) ⋅ 点赞:(0)

1.默认日志配置解析

  • access.log日志用处

    • 统计站点访问IP来源、某个时间段的访问频率
    • 查看访问最频的页面、http响应状态码、接口性能
    • 接口秒级访问量、分钟访问量、小时和天访问量
  • 默认配置解析

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
    
  • 案例

    192.168.1.1 - - [11/Apr/2024:04:48:01 +0800] "GET / HTTP/1.1" 200 615 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"
    
  • 解析

    $remote_addr:客户端IP地址
    $remote_user:远程用户
    [$time_local]:请求时间 
    "$request":请求方式
    $status:请求响应状态码
    $body_bytes_sent:响应body的大小
    "$http_referer":URL跳转来源,若是直接打开域名浏览时就会为-
    "$http_user_agent":用户终端浏览器等信息
    

2.运维统计awk

  • 查看访问最频繁的前3个IP

    awk '{print $1}' access.log | sort -n | uniq -c | sort -rn | head -n 3
    
  • 基础

    • awk是文本处理工具,默认按照空格切分,$N是切割后第几列,从1开始
    • sort命令用于将文本文件内容加以排序,-n按照数值顺序排,-r按照倒序排
    • uniq去除重复出现的行列,-c在每列旁边显示该行重复出行的次数

3.自定义日志格式

  • 日志格式增加$request_time

    • 从接收用户请求的第一个字节到发送完响应数据的时间,即包括接收请求数据时间、程序响应时间、输出响应数据时间
    • $upstream_response_time:指从nginx向后端建立连接开始到接收完数据然后关闭连接为止的时间
    • request_time一般会比upstream_response_time大,因为用户网络差或者传递数据较大时,前者会耗时大很多
  • 自定义日志配置

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
        '$status $body_bytes_sent "$http_referer" '
        '"$http_user_agent" "$http_x_forwarded_for" $request_time $upstream_response_time';
    
    ----------------------------------------------------
        
    server {
        listen       80;
        server_name  localhost a.com;
    
        access_log  logs/host.access.log  main;
    
        location / {
            root   html;
            index  index.html index.htm;
        }
        location /img {
            alias /usr/local/img/;
        }
    }
    
  • 统计耗时接口,列出传输时间超过2秒的接口,显示前3条

    cat host.access.log | awk '($25 > 2) {print $7}' | sort -n | uniq -c | sort -nr | head -3