只显示nginx访问日志中返回500状态码的日志行:css
tail -f access_log.log | grep 500 --color
注意: tail -f 以后,只能使用管道一次,以下命令将无任何输出nginx
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"';
日志内容为:tomcat
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只能用过滤方式,以下命令:code
grep -v "200" access_log.log
用sed能够用颜色标出非200的状态码:orm
为了拼出sed的正确正则表达式,咱们先从标记200为绿色开始图片
sed 's/200/\x1b[32m&\x1b[0m/g' access_log.log
说明:echo打印彩色字符时,使用八进制符号\033,可是在sed中不支持八进制,必须使用16进制:\x1brem
下一步,把状态码3XX标为黄色:form
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