Debian 下 Nginx 日志格式自定义技巧

一 基础配置步骤
http {log_format main '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';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;location / { root /var/www/html; index index.html; }}}以上路径、指令与生效方式均为 Debian 环境的通用做法。二 常用变量与格式模板
log_format upstream_time '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" "$http_user_agent" ''rt=$request_time uct="$upstream_connect_time" ''uht="$upstream_header_time" urt="$upstream_response_time"';log_format json_log escape=json'{''"@timestamp":"$time_iso8601",''"client":"$remote_addr",''"method":"$request_method",''"uri":"$request_uri",''"status":$status,''"size":$body_bytes_sent,''"responsetime":$request_time,''"upstreamtime":"$upstream_response_time",''"xff":"$http_x_forwarded_for",''"referer":"$http_referer",''"ua":"$http_user_agent"''}';三 高级用法与性能优化
server {access_log /var/log/nginx/access.log main;location /static/ {access_log off;}location /api/ {access_log /var/log/nginx/api.access.log main;}}access_log /var/log/nginx/access.log mainbuffer=32k gzip flush=1m;open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2;error_log /var/log/nginx/error.log warn;events {debug_connection 192.0.2.10;}以上用法均为 Nginx 标准指令能力,适用于 Debian 的默认安装形态。四 日志轮转与运维建议
/var/log/nginx/*.log {dailymissingokrotate 7compressdelaycompressnotifemptycreate 0640 www-data admsharedscriptspostrotateif [ -f /var/run/nginx.pid ]; thenkill -USR1 $(cat /var/run/nginx.pid)fiendscript}说明:daily 每天轮转;rotate 7 保留 7 份;compress 压缩旧日志;postrotate 向 Nginx 发送 USR1 信号让其重新打开日志文件。