til
til copied to clipboard
nginx JSON log with jq
Giả sử có log format như sau:
{
"remote_addr": "$remote_addr",
"remote_user": "$remote_user",
"time": "$time_iso8601",
"request": "$request",
"status": "$status",
"body_bytes_sent": "$body_bytes_sent",
"http_referer": "$http_referer",
"http_user_agent": "$http_user_agent",
"request_length": "$request_length",
"request_time": "$request_time",
"proxy_upstream_name": "$proxy_upstream_name",
"proxy_alternative_upstream_name": "$proxy_alternative_upstream_name",
"upstream_addr": "$upstream_addr",
"x-forwarded-for": "$http_x_forwarded_for",
"host": "$host",
"request_uri": "$request_uri",
"request_query": "$args",
"request_method": "$request_method",
"upstream_response_time": "$upstream_response_time",
"upstream_status": "$upstream_status",
"namespace": "$namespace",
"ingress_name": "$ingress_name",
"service_name": "$service_name",
"service_port": "$service_port"
}
Log output ra nhiều dòng trong một file, giờ cần xử lí bài toán như sau:
- Lọc log theo một điều kiện nào đó (ví dụ service_name hoặc path, hoặc status code)
- Group_by theo một điều kiện nào đó, ví dụ tới từ cùng một IP address hoặc UA
- Đếm số lần lặp lại của điều kiện [2]
=> Nếu format log ko phải là JSON, việc xử lí có thể sẽ khá đơn giản với awk
, tuy nhiên với JSON thì phiền phức hơn, may thay, jq
có thể xử lí multi-line như sau:
head github.com.access.log | jq -c '.| {remote_addr, status}' | sort | uniq -c | sort