nginx通过log_format定义日志格式、access_log启用,可在http/server/location块中配置;支持$remote_addr、$request_time等变量,需重载生效并验证权限与变量可用性。

Nginx 中通过 log_format 指令定义日志格式,再用 access_log 指令启用,就能自定义访问日志的输出内容和结构。
定义 log_format 格式
在 http 块(全局)或 server 块中使用 log_format,语法为:
log_format 名称 '日志模板字符串';
模板中可用变量以 $ 开头,比如 $remote_addr、$time_local、$request、$status、$body_bytes_sent 等。
常用示例:
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';在 access_log 中引用自定义格式
定义好格式后,在 http、server 或 location 块中用 access_log 启用:
access_log /var/log/nginx/access.log main;
其中 main 就是上面定义的格式名称。可同时指定多个日志文件或不同格式:
- 同一 server 下对不同 location 使用不同格式
- 将特定状态码日志单独记录(配合
if不推荐;建议用map+log_format变量控制) - 开启缓冲写入提升性能:
access_log /path/log main buffer=64k flush=5s;
常用变量与实用技巧
除了基础变量,以下变量对排障和分析很有用:
-
$request_time:请求处理总耗时(秒,精度毫秒),用于识别慢请求 -
$upstream_response_time:上游服务响应耗时(如 proxy_pass 到后端),多个值用逗号分隔 -
$http_x_real_ip或$realip_remote_addr:真实客户端 IP(需配合set_real_ip_from和real_ip_header) -
$host:请求头中的 Host 字段,比$server_name更准确反映客户端意图 - 用双引号包裹含空格的字段(如
"$request"),避免日志解析错位
验证与调试要点
修改配置后必须重载 Nginx 才生效:
nginx -t && nginx -s reload
检查日志是否按预期输出:
- 确保变量拼写正确(如
$request_time不是$req_time) - 变量在当前作用域是否可用(例如
$upstream_response_time在未使用 upstream 的 location 中为空) - 日志路径目录需有写权限,否则会静默失败
- 用
tail -f /var/log/nginx/access.log实时观察新请求输出











