nginx 自定义 access_log 格式需先在 http 块顶层用 log_format 定义(如 custom),再在 server 或 location 中通过 access_log 指令引用;变量大小写敏感、路径需有写权限,支持缓冲与定时刷盘提升性能。

要在 Nginx 配置文件中自定义 access_log 的输出格式,核心是两步:先用 log_format 定义格式,再在 access_log 指令中引用它。关键在于位置正确、变量拼写准确、路径权限到位。
log_format 必须放在 http 块内
这个指令不能写在 server 或 location 块里,否则 reload 会报错:"log_format" directive is not allowed here。只能在 http 块顶层定义:
- 打开
/etc/nginx/nginx.conf(或主配置文件),找到http { ... }区域 - 在
http块开头或中间添加类似如下定义(名称可自选,比如custom):
注意所有变量都以 $ 开头,大小写敏感,比如 $request_time 写成 $requesttime 就会留空。
在 server 或 location 中启用该格式
定义好格式后,在需要记录日志的 server 或 location 块里使用 access_log 指令,并指定格式名:
- 例如在某个
server块中写:access_log /var/log/nginx/myapp.log custom; - 路径需存在,且 Nginx 工作进程用户(如
nobody或www-data)对该目录有写权限 - 可为不同站点或路径配置不同日志路径,但复用同一个格式名即可
常用变量和实用技巧
想记录请求头里的自定义字段(如 X-Trace-ID 或 X-Forwarded-For),直接用对应小写加下划线的变量:
-
$http_x_trace_id→ 捕获客户端发来的X-Trace-ID头 -
$http_x_forwarded_for→ 获取原始客户端 IP(反向代理场景) -
$sent_http_content_type→ 记录响应头中的 Content-Type -
$upstream_response_time→ 仅代理模式有效,表示后端返回耗时
字段间建议用空格或固定分隔符(如 |),避免解析歧义;时间类变量如 $time_local 默认用本地时区。
提升性能与可靠性
日志写入支持缓冲和定时刷盘,减少磁盘 I/O:
access_log /var/log/nginx/app.log custom buffer=16k flush=5s;-
buffer=16k表示攒够 16KB 再写一次磁盘 -
flush=5s强制每 5 秒把缓冲内容写入,防止进程崩溃丢失日志 - 不加
flush时,只靠缓冲区满才写入,可能延迟较高











