log_format 必须在 http 块内定义,不可在 server 或 location 中声明;变量名严格区分大小写且以 $ 开头;引用时需显式指定格式名;推荐用分隔符或 JSON 格式避免解析歧义。

log_format 必须放在 http 块内部,不能写在 server、location 或其他嵌套块里,否则 Nginx 启动或重载时会报错:"log_format" directive is not allowed here。
必须在 http 块中定义格式
所有自定义日志格式都需在 http { ... } 大括号内声明。即使你只打算给某一个 server 使用,也得先在 http 层统一注册。例如:
- ✅ 正确位置:
http { log_format myfmt '...'; server { access_log /path/log myfmt; } } - ❌ 错误位置:
server { log_format myfmt '...'; access_log /path/log myfmt; }(直接报错)
变量名要严格匹配且区分大小写
每个变量必须以 $ 开头,拼写完全正确,否则该字段输出为空字符串(不报错但无意义):
使用ydata-profiling(前身为pandas-profiling)生成全面的数据质量报告,包含相关性分析、缺失值模式和基数检测。导出交互式HTML仪表板和JSON摘要。
-
$request_time✅;$Request_time❌;$request_time_❌ - 请求头字段统一转为小写+下划线:
$http_x_forwarded_for✅;$http-X-Forwarded-For❌ - 响应头用
$sent_http_*,如$sent_http_content_type
引用格式需显式指定名称
定义后,必须在 access_log 指令中通过名称调用,不能省略:
-
access_log /var/log/nginx/app.log myfmt;✅ -
access_log /var/log/nginx/app.log;❌(默认用 combined,不会自动匹配你定义的格式) - 同一配置中不可重复定义同名格式,否则
nginx -t校验失败
推荐加空格或固定分隔符避免解析歧义
URI 中含空格,纯靠空格分隔会导致字段错位。建议用竖线 | 或制表符分隔关键字段:
- 安全写法:
'$remote_addr | $time_iso8601 | "$request" | $status | $body_bytes_sent | $request_time | "$http_user_agent"' - JSON 输出更稳妥:
log_format json escape=json'{"ip":"$remote_addr","ts":"$time_iso8601",...}';

















