插件窝 干货文章 如何配置Nginx访问与错误日志

如何配置Nginx访问与错误日志

Nginx log 日志 配置 662    来源:    2025-04-24

Nginx访问与错误日志配置指南

Nginx提供了灵活的日志记录功能,可以帮助您监控网站流量和排查问题。以下是配置Nginx访问日志和错误日志的详细方法:

1. 基本日志配置

访问日志配置

nginx.conf或虚拟主机配置文件中添加或修改以下内容:

http {
    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;
}

错误日志配置

error_log /var/log/nginx/error.log warn;

2. 高级配置选项

日志级别

Nginx错误日志支持以下级别(从低到高): - debug (最详细) - info - notice - warn (默认) - error - crit - alert - emerg (最严重)

error_log /var/log/nginx/error.log debug;  # 开发环境使用
error_log /var/log/nginx/error.log error;  # 生产环境推荐

按虚拟主机分离日志

server {
    listen 80;
    server_name example.com;

    access_log /var/log/nginx/example.com.access.log main;
    error_log /var/log/nginx/example.com.error.log;

    # 其他配置...
}

日志缓冲和刷新

access_log /var/log/nginx/access.log main buffer=32k flush=5m;

条件日志记录

map $status $loggable {
    ~^[23]  0;  # 不记录2xx和3xx状态
    default 1;  # 记录其他状态
}

access_log /var/log/nginx/access.log main if=$loggable;

3. 日志轮转

使用logrotate

创建/etc/logrotate.d/nginx文件:

/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
    endscript
}

4. 日志格式变量

常用变量: - $remote_addr - 客户端IP - $remote_user - 认证用户名 - $time_local - 本地时间 - $request - 请求行(GET / HTTP/1.1) - $status - 响应状态码 - $body_bytes_sent - 发送给客户端的字节数 - $http_referer - 来源URL - $http_user_agent - 客户端浏览器信息 - $http_x_forwarded_for - 代理服务器IP链

5. 最佳实践

  1. 生产环境使用error级别错误日志
  2. 为每个虚拟主机配置单独的日志文件
  3. 定期轮转日志文件防止磁盘空间耗尽
  4. 敏感信息(如密码)不应记录在日志中
  5. 考虑使用JSON格式日志以便于分析: nginx log_format json_combined escape=json '{"time_local":"$time_local",' '"remote_addr":"$remote_addr",' '"remote_user":"$remote_user",' '"request":"$request",' '"status":$status,' '"body_bytes_sent":$body_bytes_sent,' '"http_referer":"$http_referer",' '"http_user_agent":"$http_user_agent",' '"http_x_forwarded_for":"$http_x_forwarded_for"}';

配置完成后,记得测试并重新加载Nginx配置:

sudo nginx -t
sudo systemctl reload nginx