Nginx日志记录配置指令详细说明以及案例
参考资料
Nginx日志记录配置指令详细说明以及案例
Nginx日志记录配置主要通过access_log和error_log指令实现。
1. access_log 指令
用于配置访问日志的路径和格式。
语法:
access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
参数说明:
path:日志文件路径。format:日志格式,默认为combined。buffer:设置缓冲区大小。gzip:启用gzip压缩。flush:设置日志刷新时间。if:条件判断。
案例:
http {
log_format custom '$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 custom buffer=32k gzip flush=5m;
}2. error_log 指令
用于配置错误日志的路径和日志级别。
语法:
error_log path [level];
参数说明:
path:日志文件路径。level:日志级别,可选debug,info,notice,warn,error,crit,alert,emerg。
案例:
error_log /var/log/nginx/error.log warn;
3. 日志格式变量
Nginx提供了多种日志格式变量,常用的有:
$remote_addr:客户端IP地址。$remote_user:客户端用户名。$time_local:本地时间。$request:请求行。$status:响应状态码。$body_bytes_sent:发送给客户端的字节数。$http_referer:请求来源。$http_user_agent:客户端浏览器信息。$http_x_forwarded_for:客户端真实IP(通过代理时)。
4. 综合案例
http {
log_format custom '$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 custom buffer=32k gzip flush=5m;
error_log /var/log/nginx/error.log warn;
server {
listen 80;
server_name example.com;
location / {
access_log /var/log/nginx/example.access.log custom;
error_log /var/log/nginx/example.error.log error;
proxy_pass http://backend;
}
}
}5. 注意事项
日志文件路径需确保Nginx有写入权限。
日志文件过大时,需定期轮转或压缩。
生产环境中建议使用
gzip压缩日志以节省磁盘空间。

