天天看点

JQ的日常使用

整理关于jq分析nginx日志的使用例子

jq的使用

在日常的使用过程中,我们可能会遇到nginx 日志格式为json,在分析过程中,就需要专业的工具对其进行格式化过滤处理,给大家推荐一下jq这个工具.

下面我就列举一下常用的jq 命令

1、筛选出指定的字段值:

cat test.log | jq -c '.upstream_addr,.upstream_response_time’  
           

2、 重新组合为新的一个json格式

cat test.log | jq -c '{"upstream":.upstream_addr,"time":.upstream_response_time}’           

3、添加过滤条件,筛选出响应时间大于10秒的请求连接,使用到jq的if...then...else...end 表达式,tonumber目的是把字符串转化成数字类型

cat test.log | jq 'if (.request_time|tonumber) >= 10  then .request_time,.url else empty end' | more           
cat test.log| jq 'if (.request_length|tonumber) >= 10000  then {"r":.request_length,"q":.body_bytes_sent,"u":.request_uri,"t":.time_local} else empty end' | more           

4、使用正则表达式

cat  test.log | jq -c  'if(.upstream_response_time|capture("(?<a>\\d+\\.\\d+)")|.a|tonumber)>5  then .  else empty end'           

后期继续更新

继续阅读