在Nginx配置文件中(通常位于/etc/nginx/nginx.conf
),可以使用log_format
指令定义自定义日志格式:
http {
log_format custom_log '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time';
access_log /var/log/nginx/access.log custom_log;
}
常用变量说明:
- $remote_addr
- 客户端IP地址
- $remote_user
- 认证用户名
- $time_local
- 本地时间
- $request
- 请求行(GET/POST等)
- $status
- 响应状态码
- $body_bytes_sent
- 发送给客户端的字节数
- $http_referer
- 来源页面
- $http_user_agent
- 客户端浏览器信息
- $request_time
- 请求处理时间(秒)
- $upstream_response_time
- 后端服务器响应时间
可以为不同server或location配置不同的日志文件:
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/example.com.access.log custom_log;
error_log /var/log/nginx/example.com.error.log;
location /api {
access_log /var/log/nginx/api.access.log custom_log;
# API相关配置
}
}
access_log /var/log/nginx/access.log custom_log buffer=64k flush=5m;
参数说明:
- buffer=size
- 设置缓冲区大小(默认64k)
- flush=time
- 设置缓冲区刷新时间(默认60秒)
access_log /var/log/nginx/access.log custom_log
buffer=256k
flush=1m
gzip=1
if=$loggable;
附加参数:
- gzip=level
- 启用gzip压缩(1-9压缩级别)
- if=condition
- 条件日志记录
对于高流量网站,还可以考虑:
open_log_file_cache
缓存日志文件描述符:open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2;
缓冲区大小选择:
刷新间隔:
日志轮转:
配置logrotate定期轮转日志文件,示例配置(/etc/logrotate.d/nginx
):
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
/usr/sbin/nginx -s reopen
endscript
}
性能监控:
配置完成后,记得测试并重新加载Nginx配置:
sudo nginx -t && sudo nginx -s reload