日常清洗 JSON 日志常用 jq 与 ripgrep 组合单行命令
几个高频但隔一阵不敲就容易忘括号位置的 jq 写法,从 shell history 里捞出来存一份:
# 1. 混杂非 JSON 行的日志流里安全过滤 5xx 并按路径统计频次
rg '"status":5\d\d' access.log | jq -R 'fromjson? | select(.) | .uri' -r \
| sort | uniq -c | sort -rn | head -n 20
# 2. 把耗时超过 1s 的请求抽成对齐的 TSV 表格
jq -r 'select(.latency_ms > 1000) | [.ts, .status, .latency_ms, .method, .uri] | @tsv' app.log \
| column -t -s $'\t'
# 3. 递归把嵌套对象里所有敏感字段打码后再发给别人排查
jq 'walk(if type == "object" and has("token") then .token = "***" else . end)' dump.json
fromjson? 这个问号特别救命,碰到程序崩溃打印出来的半截 panic 堆栈时不会直接中断整条管道。