插件窝 干货文章 如何实现Nginx的日志记录配置

如何实现Nginx的日志记录配置

日志 Nginx log 配置 499    来源:    2025-04-10

Nginx日志记录配置指南

Nginx提供了灵活的日志记录功能,可以帮助管理员监控访问情况、排查问题以及分析流量。以下是Nginx日志配置的详细说明:

1. 基本日志配置

Nginx主要有两种日志: - 访问日志(access log):记录所有客户端请求 - 错误日志(error log):记录服务器错误和警告

1.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;
}

1.2 错误日志配置

error_log /var/log/nginx/error.log warn;
# 日志级别:debug, info, notice, warn, error, crit, alert, emerg

2. 高级日志配置

2.1 按条件记录日志

# 只记录特定状态码的请求
map $status $loggable {
    ~^[23]  0;
    default 1;
}

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

# 排除特定请求(如静态文件)
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    access_log off;
}

2.2 按时间分割日志

# 在server块中使用变量实现按天分割
if ($time_iso8601 ~ "^(\d{4}-\d{2}-\d{2})") {
    set $day $1;
}

access_log /var/log/nginx/access-$day.log main;

3. 日志变量说明

常用日志变量:

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

4. 日志轮转配置

使用logrotate管理日志文件:

/etc/logrotate.d/nginx:

/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        /usr/bin/systemctl reload nginx > /dev/null 2>&1 || true
    endscript
}

5. JSON格式日志

对于日志分析工具,JSON格式更方便:

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",'
    '"request_time":$request_time,'
    '"upstream_response_time":"$upstream_response_time"}';

access_log /var/log/nginx/access.json json_combined;

6. 调试配置

临时增加调试日志:

error_log /var/log/nginx/debug.log debug;

调试完成后记得恢复为正常级别。

最佳实践建议

  1. 为不同虚拟主机配置单独的日志文件
  2. 定期检查日志文件大小并设置合理的轮转策略
  3. 敏感信息(如密码)不应记录在日志中
  4. 生产环境避免使用debug级别日志
  5. 考虑使用ELK(Elasticsearch, Logstash, Kibana)等工具集中管理日志

通过合理配置Nginx日志,您可以更好地监控服务器运行状况、分析访问模式和快速定位问题。