温馨提示×

Debian Nginx日志格式怎么改

小樊
51
2026-07-13 10:29:16
栏目: 智能运维

Debian 下修改 Nginx 日志格式,主要是修改 Nginx 配置文件 中的 log_format 指令。下面按步骤说明。


一、Nginx 日志格式在哪里改?

日志格式定义在 http 块 中,通常在以下文件之一:

  • /etc/nginx/nginx.conf
  • 或者在 /etc/nginx/conf.d/*.conf
  • 也可以在虚拟主机配置中(/etc/nginx/sites-enabled/

推荐做法
/etc/nginx/nginx.confhttp {} 块中定义日志格式。


二、查看默认日志格式

Debian 默认 Nginx 通常包含类似:

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

三、自定义日志格式(示例)

1️⃣ 修改 /etc/nginx/nginx.conf

http {
    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 /var/log/nginx/access.log main;
}

2️⃣ 常用变量说明

变量 含义
$remote_addr 客户端 IP
$remote_user 认证用户
$time_local 本地时间
$request 请求行
$status HTTP 状态码
$body_bytes_sent 发送字节数
$http_referer Referer
$http_user_agent User-Agent
$http_x_forwarded_for 代理真实 IP
$request_time 请求处理时间
$upstream_response_time 后端响应时间(反向代理)

四、为某个站点单独设置日志格式

虚拟主机配置示例

server {
    listen 80;
    server_name example.com;

    access_log /var/log/nginx/example_access.log main;
    error_log  /var/log/nginx/example_error.log;

    location / {
        root /var/www/html;
    }
}

五、常见日志格式示例

✅ JSON 格式(方便 ELK / Grafana)

log_format json_log escape=json
'{"time":"$time_iso8601",'
 '"host":"$host",'
 '"remote_addr":"$remote_addr",'
 '"request":"$request",'
 '"status":$status,'
 '"body_bytes_sent":$body_bytes_sent,'
 '"request_time":$request_time,'
 '"http_referer":"$http_referer",'
 '"http_user_agent":"$http_user_agent"}';

使用:

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

六、修改后必须执行

nginx -t        # 检查配置
systemctl reload nginx

或:

service nginx reload

七、日志位置(Debian 默认)

/var/log/nginx/access.log
/var/log/nginx/error.log

如果你有 具体需求(比如:记录真实 IP、记录请求耗时、JSON 格式、按日期切割日志),可以直接告诉我,我帮你写完整配置。

0