Nginx 访问日志配置

JSON 访问日志便于 Filebeat、Logstash 和检索工具直接解析,减少复杂正则。

JSON 日志格式

log_format json escape=json '{'
    '"time":"$time_iso8601",'
    '"remote_addr":"$remote_addr",'
    '"host":"$host",'
    '"request":"$request",'
    '"status":$status,'
    '"bytes":$body_bytes_sent,'
    '"request_time":$request_time,'
    '"upstream_addr":"$upstream_addr",'
    '"upstream_time":"$upstream_response_time",'
    '"cache":"$upstream_cache_status",'
    '"user_agent":"$http_user_agent"'
'}';

server {
    server_name example.com;
    access_log /var/log/nginx/example.json.log json;
}

验证 JSON

curl -s http://127.0.0.1/ >/dev/null
tail -n 1 /var/log/nginx/example.json.log | python3 -m json.tool

注意