打开配置文件
通常位于 /etc/nginx/nginx.conf
或 /etc/nginx/conf.d/*.conf
,使用文本编辑器修改:
sudo nano /etc/nginx/nginx.conf
定义日志格式
在 http
块中使用 log_format
指令自定义格式,变量用 $
开头,常用变量包括:
$remote_addr
:客户端IP$request
:请求行(方法+URI+协议)$status
:响应状态码$body_bytes_sent
:响应体字节数$request_time
:请求处理总时间(秒)$upstream_response_time
:后端响应时间(反向代理场景)http {
log_format custom '$remote_addr - $request $status $body_bytes_sent $request_time';
# 其他配置...
}
应用日志格式
在 server
或 location
块中通过 access_log
指令引用自定义格式:
server {
access_log /var/log/nginx/access.log custom;
# 其他配置...
}
重启Nginx生效
sudo nginx -s reload
默认格式(combined)
log_format combined '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
JSON格式
适合日志分析工具(如ELK):
log_format json '{ "time": "$time_iso8601", "ip": "$remote_addr", "request": "$request", "status": $status }';
带缓冲的格式
提升高流量场景性能,按指定大小或时间写入磁盘:
access_log /var/log/nginx/access.log custom buffer=32k flush=5m;
条件日志记录
通过 map
指令过滤不需要记录的请求(如静态资源):
map $uri $loggable {
~^/static/ 0;
default 1;
}
access_log /var/log/nginx/access.log custom if=$loggable;
多日志文件分离
按虚拟主机或路径拆分日志:
server {
server_name site1.example.com;
access_log /var/log/nginx/site1.access.log custom;
}
日志轮转管理
配合 logrotate
工具避免日志占满磁盘,示例配置:
# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
rotate 7
compress
missingok
create 0640 www-data adm
postrotate
/usr/sbin/nginx -s reload
endscript
}
chown -R www-data:www-data /var/log/nginx
)。buffer
)或异步写入(如通过管道输出到远程服务器)。配置参考来源: