nginx log记录请求响应日志及日志分割
之前部署了quic的集群在aws,在測試的時候發現在大報文的情形下HTTP3的請求耗時比較不穩定,并且耗時比普通的HTTP2要大很多,就想看看請求的具體耗時有多少
請求響應日志記錄
我的quic集群是通過nginx部署的,所有的請求都是由nginx轉發的,只要在nginx里記錄請求日志就可以了,通過修改nginx配置文件nginx.conf里的log_format指令參數就可以做到
log_format指令是用來控制nginx如何記錄http請求, 默認的nginx記錄日志格式是注釋掉的,如果要記錄額外的信息,需要自定義log_format格式
我的目的是為了記錄請求的耗時,就可以添加如下的log_format格式
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';然后引用這個新的日志格式
access_log logs/access.log main;修改配置后,nginx的訪問日志如下:
幾個時間變量的意義:
- $request_time – Full request time, starting when NGINX reads the first byte from the client and ending when NGINX sends the last byte of the response body
- $upstream_connect_time – Time spent establishing a connection with an upstream server
- $upstream_header_time – Time between establishing a connection to an upstream server and receiving the first byte of the response header
- $upstream_response_time – Time between establishing a connection to an upstream server and receiving the last byte of the response body
$request_time : 就是指從nginx接受用戶請求的第一個字節到發送完響應數據的時間,即包括接收請求數據時間、程序響應時間、輸出響應時間等
$upstream_response_time: 是指從nginx向后端建立連接開始到接收到程序處理后的響應的最后一個字節的時間
有了請求響應的日志,我們就可以借助awk文本處理命令來統計access.log
統計nginx訪問日志access.log的每分鐘請求數
awk -F: '{count[$2":"$3]++} END {for (minute in count) print minute, count[minute]}' ./access.log | sort > count.log統計請求響應時間超過10秒的記錄
awk '($NF > 10){print $0}' ./access.log > request_time_gt_10.log日志分割
1.編寫shell腳本
nginx_log_task.sh
#!/bin/bash #設置日志文件存放目錄 logs_path="/opt/server/nginx/logs/" #設置pid文件 pid_path="/opt/server/nginx/logs/nginx.pid" #重命名日志文件 mv ${logs_path}access.log ${logs_path}access_$(date -d "yesterday" +"%Y%m%d").log #重命名異常文件 mv ${logs_path}error.log ${logs_path}error_$(date -d "yesterday" +"%Y%m%d").log #發送kill -USR1信號給nginx的主進程號,讓nginx重新生成一個新的日志文件 kill -USR1 `cat ${pid_path}` #將5天前的日志刪除 find /opt/server/nginx/logs/ -mtime +5 -name "*.log" -exec rm -rf {} \;2.添加定時任務
crontab -e #每天凌晨00:00定時執行這個腳本 00 00 * * * /opt/nginx_log_task.sh參考資料:
Using NGINX Logging for Application Performance Monitoring
總結
以上是生活随笔為你收集整理的nginx log记录请求响应日志及日志分割的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Idea单测执行报错“Command l
- 下一篇: 使用mybatis-generator自