温馨提示×

nginx日志格式可以自定义吗

小樊
42
2026-10-11 12:13:58
栏目: 编程语言

可以的,Nginx 的日志格式是完全支持自定义的。


一、通过 log_format 自定义日志格式

在 http 块中使用 log_format 指令定义日志格式:

http {
    log_format main '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent"';

    access_log /var/log/nginx/access.log main;
}

常用变量说明

变量 含义
$remote_addr 客户端 IP
$time_local 访问时间
$request 请求行(方法 + URI + 协议)
$status HTTP 状态码
$body_bytes_sent 发送给客户端的字节数
$http_referer 来源页
$http_user_agent 客户端浏览器/代理
$request_time 请求处理总时间
$upstream_response_time 后端响应时间

二、示例:更详细的日志格式(常用于排查问题)

log_format detailed '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    'rt=$request_time uct="$upstream_connect_time" '
                    'urt="$upstream_response_time" '
                    'cs=$upstream_cache_status';

三、不同 location / server 使用不同日志

server {
    access_log /var/log/nginx/api.log main;
}

location /static/ {
    access_log off;
}

四、注意事项

  1. log_format 只能定义在 http 块中
  2. 修改后需 nginx -s reload
  3. 日志太详细会影响磁盘 IO(高并发场景需权衡)

如果你有具体想记录的字段(如 JWT、traceId、真实客户端 IP),我可以帮你写完整配置。

0 踩