【Nginx知识】nginx日志配置详解

Nginx 日志格式配置全面指南

一、核心日志配置指令

1. log_format 指令语法

log_format format_name 'string_format';

2. access_log 指令语法

access_log path [format [buffer=size] [gzip[=level]] [flush=time]];

二、完整可配置字段列表

1. 基础请求信息

变量说明示例值
$remote_addr客户端IP地址192.168.1.100
$remote_user客户端用户名(基本认证)admin
$time_local本地时间(通用日志格式)01/Jan/2023:12:34:56 +0800
$time_iso8601ISO8601格式时间2023-01-01T12:34:56+08:00
$request完整请求行GET /index.html HTTP/1.1
$request_method请求方法GET, POST
$request_uri完整请求URI(含参数)/search?q=nginx
$uri请求URI(不含参数)/search
$args查询字符串q=nginx&page=1
$query_string$argsq=nginx&page=1
$server_protocol请求协议HTTP/1.1
$server_name服务器名称example.com
$server_addr服务器IP地址192.168.1.1
$server_port服务器端口80, 443
$status响应状态码200, 404, 500
$body_bytes_sent发送给客户端的字节数1024
$bytes_sent发送的总字节数(含头)1256
$request_length请求长度(含头)356

2. 连接与性能指标

变量说明示例值
$connection连接序列号123456
$connection_requests当前连接上的请求数5
$request_time请求处理时间(秒)0.056
$upstream_response_time后端响应时间0.045
$upstream_connect_time连接后端时间0.012
$upstream_header_time首字节时间0.023
$pipe是否使用管道p (pipelined)
$msec当前时间(毫秒精度)1672547696.123

3. HTTP 头信息

变量说明示例值
$http_user_agent客户端浏览器信息Mozilla/5.0
$http_referer来源页面URLhttps://google.com
$http_host请求主机头www.example.com
$http_x_forwarded_for代理链IP地址192.168.1.100, 10.0.0.1
$http_cookieCookie信息sessionid=abc123
$http_accept_language客户端语言en-US,en;q=0.9
$http_accept_encoding客户端编码gzip, deflate
$http_accept客户端接受类型text/html
$http_authorization认证信息Basic YWRtaW46cGFzc3dvcmQ=

4. 反向代理相关

变量说明示例值
$upstream_addr后端服务器地址10.0.0.2:8080
$upstream_status后端响应状态码200
$upstream_cache_status缓存状态HIT, MISS, EXPIRED
$upstream_http_*后端响应头$upstream_http_server
$proxy_host代理主机名backend-server
$proxy_port代理端口8080

5. SSL/TLS 信息

变量说明示例值
$ssl_protocolSSL协议版本TLSv1.2
$ssl_cipher加密套件ECDHE-RSA-AES128-GCM-SHA256
$ssl_session_idSSL会话IDabcdef1234567890
$ssl_session_reused会话重用r (reused)
$ssl_client_cert客户端证书-----BEGIN CERTIFICATE-----...
$ssl_client_verify客户端证书验证SUCCESS, FAILED
$ssl_server_nameSNI服务器名secure.example.com

三、日志格式配置示例

1. 基础日志格式

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

2. 扩展日志格式(含性能指标)

log_format extended '$remote_addr - $remote_user [$time_iso8601] '
                   '"$request_method $request_uri $server_protocol" '
                   '$status $body_bytes_sent "$http_referer" '
                   '"$http_user_agent" "$http_x_forwarded_for" '
                   'rt=$request_time uct=$upstream_connect_time '
                   'uht=$upstream_header_time urt=$upstream_response_time '
                   'cs=$upstream_cache_status';

3. JSON 格式日志

log_format json escape=json '{'
    '"time": "$time_iso8601", '
    '"remote_addr": "$remote_addr", '
    '"remote_user": "$remote_user", '
    '"request": "$request", '
    '"status": "$status", '
    '"body_bytes_sent": "$body_bytes_sent", '
    '"request_time": "$request_time", '
    '"http_referer": "$http_referer", '
    '"http_user_agent": "$http_user_agent", '
    '"http_x_forwarded_for": "$http_x_forwarded_for", '
    '"upstream_response_time": "$upstream_response_time", '
    '"upstream_cache_status": "$upstream_cache_status"'
'}';

四、高级配置技巧

1. 条件日志记录

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

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

2. 多日志文件分离

# 错误日志单独记录
map $status $error_log {
    ~^[45]  1;  # 4xx/5xx错误
    default 0;
}

access_log /var/log/nginx/error.log combined if=$error_log;
access_log /var/log/nginx/access.log combined;

3. 性能优化配置

access_log /var/log/nginx/access.log combined 
    buffer=32k  # 32KB缓冲区
    flush=5m;   # 5分钟刷新

五、完整配置示例

http {
    # 定义日志格式
    log_format main '$remote_addr - $remote_user [$time_local] '
                   '"$request" $status $body_bytes_sent '
                   '"$http_referer" "$http_user_agent"';
    
    log_format extended '$remote_addr - $remote_user [$time_iso8601] '
                      '"$request_method $request_uri $server_protocol" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for" '
                      'rt=$request_time uct=$upstream_connect_time '
                      'uht=$upstream_header_time urt=$upstream_response_time '
                      'cs=$upstream_cache_status';
    
    log_format json escape=json '{'
        '"time": "$time_iso8601", '
        '"remote_addr": "$remote_addr", '
        '"remote_user": "$remote_user", '
        '"request": "$request", '
        '"status": "$status", '
        '"body_bytes_sent": "$body_bytes_sent", '
        '"request_time": "$request_time", '
        '"http_referer": "$http_referer", '
        '"http_user_agent": "$http_user_agent", '
        '"http_x_forwarded_for": "$http_x_forwarded_for", '
        '"upstream_response_time": "$upstream_response_time", '
        '"upstream_cache_status": "$upstream_cache_status"'
    '}';
    
    # 条件日志记录
    map $status $loggable {
        default 1;
        "499"  0;  # 不记录客户端断开连接
    }
    
    map $status $error_status {
        ~^[45]  1;  # 4xx/5xx错误
        default 0;
    }
   
    server {
        listen 80;
        server_name example.com;
        
        # 主访问日志
        access_log /var/log/nginx/access.log extended buffer=32k flush=5m if=$loggable;
        
        # 错误日志单独记录
        access_log /var/log/nginx/error.log extended if=$error_status;
        
        # JSON格式日志
        access_log /var/log/nginx/access.json json;
        
        location / {
            proxy_pass http://backend;
            proxy_set_header Host $host;
            
            # 记录后端信息
            log_format backend '$remote_addr - $upstream_addr [$time_iso8601] '
                              '"$request" $upstream_status $body_bytes_sent '
                              'rt=$request_time urt=$upstream_response_time';
            access_log /var/log/nginx/backend.log backend;
        }
        
        # 静态文件不记录
        location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
            access_log off;
            expires 30d;
        }
    }
}

六、日志分析建议

1. 推荐字段组合

场景推荐字段
基础监控$remote_addr, $time_iso8601, $request, $status, $body_bytes_sent
性能分析$request_time, $upstream_response_time, $upstream_connect_time, $upstream_header_time
安全审计$http_user_agent, $http_referer, $http_x_forwarded_for, $request_method
缓存优化$upstream_cache_status, $uri, $args
SEO分析$http_referer, $http_user_agent, $uri, $args

2. 日志轮转配置

# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        /usr/bin/systemctl reload nginx > /dev/null
    endscript
}

七、常见问题解决

1. 日志字段为空

# 确保变量在正确上下文中可用
# SSL变量只在HTTPS服务器中有效
# 上游变量只在代理请求中有效

2. 特殊字符处理

# JSON格式使用escape=json
log_format json escape=json '{...}';

# CSV格式处理逗号
log_format csv '$remote_addr,$time_local,"$request",$status';

3. 性能影响优化

# 减少日志字段数量
# 增加缓冲区大小
# 关闭静态资源日志
# 使用syslog代替文件

八、最佳实践总结

  1. 格式选择原则

    • 调试分析:使用扩展格式
    • 日志分析系统:使用JSON格式
    • 兼容性:使用基础格式
  2. 关键字段包含

    # 必须包含的字段
    $time_iso8601, $remote_addr, $request_method, $request_uri, $status, $request_time
    
  3. 安全注意事项

    • 避免记录敏感信息(密码、token)
    • 限制日志文件权限
    • 定期清理历史日志
  4. 性能优化

    access_log /path/to/log buffer=64k flush=10m;
    location ~* \.(static)$ { access_log off; }
    
  5. 监控字段

    • 错误率:$status ~ "^[45]"
    • 慢请求:$request_time > 1
    • 缓存命中率:$upstream_cache_status

通过合理配置Nginx日志格式,您可以获得丰富的运维洞察力,有效监控服务性能和安全性。

相关文献

【nginx知识】弄懂nginx看这一篇文章就够了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

问道飞鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值