nginx自1.9.0开始提供tcp/udp的反向代理功能,直到1.11.4才开始提供session日志功能。
启用stream日志配置文件
主配置文件/etc/nginx/nginx.conf增加内容:
stream { log_format proxy '$remote_addr [$time_local] ' '$protocol $status $bytes_sent $bytes_received ' '$session_time "$upstream_addr" ' '"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"'; access_log /var/log/nginx/tcp-access.log proxy ; open_log_file_cache off; include /etc/nginx/conf.d/*.stream;}
具体的tcp.stream配置文件
upstream TCP59001 { hash $remote_addr consistent; server 192.168.1.176:59001; } server { listen 59001; proxy_connect_timeout 5s; proxy_timeout 30s; proxy_pass TCP59001; }
nginx重读配置并检查tcp session日志的生成
nginx重读配置
nginx -s reload
检查日志
tail /var/log/nginx/tcp-access.log
192.168.3.218 [25/Apr/2017:17:55:57 +0800] TCP 200 103 122 10.671 "192.168.1.176:59001" "122" "103" "0.000"192.168.3.218 [25/Apr/2017:17:55:57 +0800] TCP 200 55 74 4.714 "192.168.1.176:59001" "74" "55" "0.000"192.168.3.218 [25/Apr/2017:17:55:57 +0800] TCP 200 71 90 6.171 "192.168.1.176:59001" "90" "71" "0.000"192.168.3.218 [25/Apr/2017:17:55:57 +0800] TCP 200 55 74 4.707 "192.168.1.176:59001" "74" "55" "0.000"192.168.9.1 [25/Apr/2017:18:49:20 +0800] TCP 200 3423 3438 3375.851 "192.168.1.176:59003" "3438" "3423" "0.000"192.168.9.1 [25/Apr/2017:18:54:55 +0800] TCP 200 359 374 334.827 "192.168.1.176:59001" "374" "359" "0.001"
至此配置已经完成,upstream的日志已经顺利记录到文件。
配置经验
- 测试发现nginx会等待session结束才会记录到日志文件;
- session日志只是tcp层面的记录,包括session时间,发送接收字节数等等;
- session内部发送日志(比如一个socket连接建立起来以后,多次发送心跳数据)需要在应用层面才能记录;
参考
log_format 能取到的变量可从此查询