# Nginx Access Log 改 Json 格式 ## 調整 nginx config ```json http { ....略 # 設定成json格式 log_format jsonlog '{' '"host":"$host",' '"remote_addr":"$remote_addr",' '"logtime":"$time_iso8601",' '"request":"$request",' '"status":$status,' '"body_bytes_sent":$body_bytes_sent,' '"http_referer":"$http_referer",' '"http_user_agent":"$http_user_agent",' '"request_time":$request_time,' '"upstream_response_time":"$upstream_response_time"' '}'; # 設定 access_log 改用上面的json設定 access_log /var/log/nginx/access.log jsonlog; ``` ## 完成後 access.log 就會變成 json 格式 後續就可以直接利用duckdb對nginx log 查詢例如: ```SQL cat /var/log/nginx/access.log | duckdb -markdown -s " select remote_addr , sum(case when status between 400 and 499 then 1 else 0 end) Status4xx , sum(case when status between 500 and 599 then 1 else 0 end) Status5xx , count(*) acount from read_json_auto('/dev/stdin',ignore_errors=true) where status between 400 and 599 group by remote_addr order by acount desc " ``` ![image](https://hackmd.io/_uploads/S1Gg8AEl1g.png) 就可以根據IP統計 400~500 錯誤的請求。 ## 網路參考 * [duckdb](https://duckdb.org/) * [Module ngx_http_log_module ](https://nginx.org/en/docs/http/ngx_http_log_module.html)