温馨提示×

nginx日志格式怎样修改

小樊
49
2026-09-17 19:21:03
栏目: 编程语言

在 Nginx 中,日志格式是通过 log_format 指令定义的,然后在 access_log 指令中引用。


一、修改日志格式的基本步骤

1️⃣ 定义日志格式(log_format)

一般在 http 块中(通常是 nginx.conf 或 conf.d/*.conf):

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;
}

2️⃣ 在 server 或 location 中使用

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

⚠️ 修改后必须重载 Nginx

nginx -t
nginx -s reload

二、常用日志变量说明

变量 含义
$remote_addr 客户端 IP
$remote_user 认证用户
$time_local 访问时间
$request 请求行
$status HTTP 状态码
$body_bytes_sent 响应字节数
$http_referer 来源页
$http_user_agent 客户端浏览器
$request_time 请求总耗时
$upstream_response_time 后端响应时间
$host 域名

三、常见自定义示例

✅ 示例 1:包含请求耗时(推荐)

log_format json_log '{'
    '"time":"$time_local",'
    '"remote_addr":"$remote_addr",'
    '"request":"$request",'
    '"status":$status,'
    '"request_time":$request_time,'
    '"upstream_time":"$upstream_response_time"'
'}';

✅ 示例 2:JSON 格式(方便 ELK / Loki)

access_log /var/log/nginx/access.log json_log;

✅ 示例 3:只记录错误请求

map $status $loggable {
    ~^[45]  1;
    default 0;
}

access_log /var/log/nginx/error.log main if=$loggable;

四、注意事项

  • log_format 只能定义在 http 块
  • 名字不能重复
  • 已存在的日志不会重新生成,只影响新日志
  • 高并发场景建议精简字段,减少 IO

如果你有 具体需求(比如 JSON 格式、按域名、按接口、接入日志系统),我可以帮你直接写一份配置。

0 踩