nginx日志配置
Nginx 日志记录服务运行状态和访问信息,是运维排查的重要工具。
访问日志
access_log 指令
nginx
access_log /var/log/nginx/access.log;
自定义日志格式
nginx
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent"';
access_log /var/log/nginx/access.log main;
}
常用日志变量
| 变量 | 说明 |
|---|---|
$remote_addr | 客户端 IP |
$time_local | 请求时间 |
$request | 请求行 |
$status | 响应状态码 |
$body_bytes_sent | 发送字节数 |
$request_time | 请求处理时间 |
$http_referer | 来源 URL |
$http_user_agent | 客户端标识 |
错误日志
error_log 指令
nginx
error_log /var/log/nginx/error.log warn;
日志级别
| 级别 | 说明 |
|---|---|
| debug | 调试信息 |
| info | 一般信息 |
| notice | 重要提示 |
| warn | 警告 |
| error | 错误 |
| crit | 严重错误 |
| alert | 需立即处理 |
| emerg | 紧急状态 |
分层级配置
在不同配置段分别设置日志:
nginx
http {
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
server {
# 覆盖全局日志
access_log /var/log/nginx/site.access.log main;
error_log /var/log/nginx/site.error.log error;
}
}
日志缓冲
nginx
access_log /var/log/nginx/access.log main buffer=32k flush=5s;
关闭日志
nginx
location /health {
access_log off;
log_not_found off;
}
注意事项
- 子配置段继承父配置段日志,如需覆盖需重新声明
- buffer 提升性能但崩溃时会丢失未刷盘数据
- 生产环境 error_log 建议 error 或 warn 级别
条件日志
nginx
map $status $should_log {
~^[23] 0;
default 1;
}
access_log /var/log/nginx/error_only.log main if=$should_log;
要点总结
- access_log 配置访问日志,error_log 配置错误日志
- log_format 自定义日志格式,使用变量提取字段
- error_log 支持 8 个级别,生产建议 warn 或 error
- buffer 参数缓冲日志写入,提升性能
- 子配置段继承父配置段日志,可覆盖或关闭
📝 发现内容有误?点击此处直接编辑