在 Debian 下修改 Nginx 日志格式,主要是修改 Nginx 配置文件 中的 log_format 指令。下面按步骤说明。
日志格式定义在 http 块 中,通常在以下文件之一:
/etc/nginx/nginx.conf/etc/nginx/conf.d/*.conf/etc/nginx/sites-enabled/)✅ 推荐做法:
在 /etc/nginx/nginx.conf 的 http {} 块中定义日志格式。
Debian 默认 Nginx 通常包含类似:
http {
log_format combined '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
}
/etc/nginx/nginx.confhttp {
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;
}
| 变量 | 含义 |
|---|---|
$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;
}
}
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
/var/log/nginx/access.log
/var/log/nginx/error.log
如果你有 具体需求(比如:记录真实 IP、记录请求耗时、JSON 格式、按日期切割日志),可以直接告诉我,我帮你写完整配置。