插件窝 干货文章 Nginx日志格式如何配置

Nginx日志格式如何配置

Nginx log 日志 remote 150    来源:    2025-04-24

Nginx日志格式配置详解

Nginx的日志格式可以通过log_format指令进行自定义配置,以下是全面的配置指南:

基本配置方法

在nginx.conf配置文件中(通常在http块中)配置日志格式:

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地址
$remote_user 客户端用户名(基本认证)
$time_local 本地时间(Common Log Format)
$request 完整的原始请求行
$status 响应状态码
$body_bytes_sent 发送给客户端的字节数(不含头)
$http_referer 请求来源页
$http_user_agent 客户端浏览器信息
$http_x_forwarded_for 代理服务器IP链
$request_time 请求处理时间(秒)
$upstream_response_time 后端服务器响应时间

高级日志格式示例

1. 包含响应时间的日志

log_format timed_combined '$remote_addr - $remote_user [$time_local] '
                         '"$request" $status $body_bytes_sent '
                         '"$http_referer" "$http_user_agent" '
                         '$request_time $upstream_response_time';

2. 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",'
    '"request_time":"$request_time",'
    '"http_referrer":"$http_referer",'
    '"http_user_agent":"$http_user_agent"}';

3. 包含HTTPS信息的日志

log_format ssl_combined '$remote_addr - $remote_user [$time_local] '
                        '"$request" $status $body_bytes_sent '
                        '"$http_referer" "$http_user_agent" '
                        '$ssl_protocol/$ssl_cipher';

多日志文件配置

可以为不同server或location配置不同的日志:

server {
    access_log /var/log/nginx/example.com.access.log main;
    access_log /var/log/nginx/example.com.timing.log timed_combined;

    location /api/ {
        access_log /var/log/nginx/api.access.log json_combined;
    }
}

日志轮转

建议使用logrotate管理日志文件,示例配置:

/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
}

性能优化提示

  1. 对于高流量站点,可以缓冲日志写入:

    access_log /path/to/log.gz combined gzip=1 buffer=32k flush=5m;
    
  2. 可以关闭不需要的日志记录:

    access_log off;  # 完全关闭访问日志
    
  3. 对于静态文件,可以单独配置不记录:

    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
       access_log off;
    }
    

通过合理配置日志格式,可以更好地监控和分析Nginx服务器的运行状况。