Nginx中配置JSON日志需在http块用单引号定义log_format,键和字符串值均用双引号,变量直接插入;应用时指定access_log路径与格式名;对含特殊字符的变量(如$http_user_agent)应配合map预处理;最后用python3 -m json.tool校验合法性。
在 Nginx 中使用 log_format 输出 JSON 格式日志,核心是定义一个包含变量的 JSON 字符串格式,并确保特殊字符(如双引号、空格)被正确转义或引用。Nginx 本身不解析 JSON,只是拼接字符串,所以关键在于格式合法、可被下游日志系统(如 Filebeat、Loki、ELK)直接消费。
在 http 块中定义 log_format,用单引号包裹整个格式字符串,避免 shell 或配置解析干扰;JSON 内部字段名和字符串值都用双引号,变量(如 $time_local)直接插入:
"status": "$status"
示例:
log_format json '{"time":"$time_iso8601","remote_addr":"$remote_addr","host":"$host","request_uri":"$request_uri","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"}';在 server 或 location 块中调用该格式:
json),支持追加 buffer 和 flush 提升性能示例:
access_log /var/log/nginx/access.json json buffer=32k flush=1s;$http_user_agent 或 $http_referer 可能含双引号、换行符,直接插入 JSON 会导致解析失败。Nginx 的 map 指令可做简单替换:
示例:
map $http_user_agent $ua_json {default "$http_user_agent";
~"[""nrt]" "invalid_ua";
}
log_format json '{"user_agent":"$ua_json",...}';
JSON 日志是否合法,不能只靠肉眼检查:
nginx -t 确认配置语法无误(它不校验 JSON 结构)tail -1 /var/log/nginx/access.json | python3 -m json.tool 格式化校验"ref": $http_referer → "ref": ),务必给所有字符串变量加引号