nginx日志文件分析以及添加接口响应耗时

access.log日志用处

122.70.148.18 - - [04/Aug/2020:14:46:48 +0800] “GET /user/api/v1/product/order/query_state?product_id=1&token=xdclasseyJhbGciOJE HTTP/1.1” 200 48 “https://xdclass.net/” “Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36” 解析

$remote_addr 对应的是真实日志里的122.70.148.18,即客户端的IP。 r e m o t e u s e r 对 应 的 是 第 二 个 中 杠 “ − ” , 没 有 远 程 用 户 , 所 以 用 “ − ” 填 充 。 [ remote_user 对应的是第二个中杠“-”,没有远程用户,所以用“-”填充。 [ remoteuser对应的是第二个中杠“−”,没有远程用户,所以用“−”填充。[time_local]对应的是[04/Aug/2020:14:46:48 +0800]。 “$request”对应的是"GET /user/api/v1/product/order/query_state?product_id=1&token=xdclasseyJhbGciOJE HTTP/1.1"。 $status对应的是200状态码,200表示正常访问。 b o d y b y t e s s e n t 对 应 的 是 48 字 节 , 即 响 应 b o d y 的 大 小 。 “ body_bytes_sent对应的是48字节,即响应body的大小。 “ bodybytessent对应的是48字节,即响应body的大小。“http_referer” 对应的是”https://xdclass.net/“,若是直接打开域名浏览的时,referer就会没有值,为”-“。 “ h t t p u s e r a g e n t ” 对 应 的 是 ” M o z i l l a / 5.0 ( M a c i n t o s h ; I n t e l M a c O S X 10.12 ; r v : 56.0 ) G e c k o / 20100101 F i r e f o x / 56.0 ” 。 “ http_user_agent” 对应的是”Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:56.0) Gecko/20100101 Firefox/56.0”。 “ httpuseragent”对应的是”Mozilla/5.0(Macintosh;IntelMacOSX10.12;rv:56.0)Gecko/20100101Firefox/56.0”。“http_x_forwarded_for” 对应的是”-“或者空。

自定义日志格式,统计接口响应耗时

日志格式增加 $request_time

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

配置自定义日志格式

log_format main $remote_addr - r e m o t e u s e r [ remote_user [ remoteuser[time_local] “KaTeX parse error: Double superscript at position 33: … ̲status b o d y b y t e s s e n t " body_bytes_sent " bodybytessent"http_referer” ’ ‘“ h t t p u s e r a g e n t " " http_user_agent" " httpuseragent""http_x_forwarded_for” $request_time’; server { listen 80; server_name aabbcc.com; location / { root /usr/local/nginx/html; index xdclass.html; } #charset koi8-r; # access_log logs/host.access.log main; }

统计耗时接口, 列出传输时间超过 2 秒的接口,显示前5条

cat time_temp.log|awk ($NF > 2){print KaTeX parse error: Expected EOF, got } at position 2: 7}̲|sort -n|uniq …NF 表示最后一列, awk ‘{print $NF}’

经验分享 程序员 微信小程序 职场和发展