nginx日志分析 - 用sed彩色标记特定内容
jopen
10年前
实时过滤日志
只显示nginx访问日志中返回500状态码的日志行:
tail -f access_log.log | grep 500 --color
注意: tail -f 之后,只能使用管道一次,如下命令将无任何输出
tail -f access_log.log | grep 500 | grep 500
用颜色标记日志中的特定内容
比如,nginx日志格式为:
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.181 - - [13/Apr/2011:15:19:10 +0800] "GET /tomcat.png HTTP/1.1" 304 0 "http://192.168.1.9/" "Mozilla/5.0 (Windows NT 6.1; rv:2.0) Gecko/20100101 Firefox/4.0" "-" 192.168.1.181 - - [13/Apr/2011:15:19:10 +0800] "GET /favicon.ico HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 6.1; rv:2.0) Gecko/20100101 Firefox/4.0" "-" 192.168.1.181 - - [13/Apr/2011:15:19:10 +0800] "GET /bg-nav.png HTTP/1.1" 304 0 "http://192.168.1.9/tomcat.css" "Mozilla/5.0 (Windows NT 6.1; rv:2.0) Gecko/20100101 Firefox/4.0" "-" 192.168.1.181 - - [13/Apr/2011:15:19:10 +0800] "GET /bg-upper.png HTTP/1.1" 304 0 "http://192.168.1.9/tomcat.css" "Mozilla/5.0 (Windows NT 6.1; rv:2.0) Gecko/20100101 Firefox/4.0" "-" 192.168.1.181 - - [13/Apr/2011:15:19:10 +0800] "GET /bg-middle.png HTTP/1.1" 304 0 "http://192.168.1.9/tomcat.css" "Mozilla/5.0 (Windows NT 6.1; rv:2.0) Gecko/20100101 Firefox/4.0" "-" 192.168.1.181 - - [13/Apr/2011:15:19:10 +0800] "GET /bg-button.png HTTP/1.1" 304 0 "http://192.168.1.9/tomcat.css" "Mozilla/5.0 (Windows NT 6.1; rv:2.0) Gecko/20100101 Firefox/4.0" "-" 192.168.1.114 - - [13/Apr/2011:15:19:37 +0800] "GET / HTTP/1.0" 200 12220 "-" "-" "-" 192.168.1.114 - - [13/Apr/2011:15:20:22 +0800] "GET / HTTP/1.0" 200 12220 "-" "-" "-"
需求:标出返回状态码非200的请求
如果用grep只能用过滤方式,如下命令:
grep -v "200" access_log.log
用sed可以用颜色标出非200的状态码:
为了拼出sed的正确正则表达式,我们先从标记200为绿色开始
sed 's/200/\x1b[32m&\x1b[0m/g' access_log.log
说明:echo打印彩色字符时,使用八进制符号\033,但是在sed中不支持八进制,必须使用16进制:\x1b
下一步,把状态码3XX标为黄色:
sed 's/3[0-9][0-9]/\x1b[33m&\x1b[0m/g' access_log.log
但请注意,nginx日志行中其他地方也有数字,上面的匹配不够精确
下一步,把HTTP/1.0” 或者 HTTP/1.1"之后的3位数标记颜色:
sed 's/\(HTTP\/1\.[01]" \)\(3[0-9][0-9]\)/\1\x1b[33m\2\x1b[0m/g' access_log.log
再下一步,如果状态码之后的返回数据量大于1K,就标记红色:
sed 's/\(HTTP\/1\.[01]" [0-9][0-9][0-9] \)\([0-9]\+\)[0-9][0-9][0-9]/\1\x1b[31m[\2KB]\x1b[0m/g' access_log.log