Nginx通过log_format定义日志格式、access_log启用记录,支持自定义变量、缓冲、条件写入及多日志输出;需重载生效,注意变量拼写、权限与性能。
Nginx 的 access_log 指令配合 log_format 可以灵活控制访问日志的输出内容和格式,满足调试、监控、审计等不同场景需求。
在 http 块中使用 log_format 定义日志模板,名称需唯一,后续通过名称引用:
main、with_time)$ 开头,常见变量包括:$remote_addr(客户端IP)、$time_local(本地时间)、$request(完整请求行)、$status(响应状态码)、$body_bytes_sent(响应体字节数)、$http_user_agent(User-Agent)、$http_referer(来源页)$upstream_http_x_trace_id 或 $sent_http_content_type),但需确保上游服务实际返回对应头用 access_log 指令指定日志路径和使用的格式名,可同时配置缓冲、刷盘、条件记录等:
access_log /var/log/nginx/app.log with_time;
access_log /var/log/nginx/app.log with_time buffer=64k;
access_log /var/log/nginx/error_access.log main if=$bad_request;,需提前定义 map 变量 $bad_request
access_log 指令可共存,实现同一请求写入多份日志(如一份全量,一份仅错误)根据典型需求快速复用:
log_format detailed '$time_iso8601.$msec $remote_addr "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" $request_time $upstream_response_time';
log_format json '{"time":"$time_iso8601","remote":"$remote_addr","method":"$request_method","uri":"$request_uri","status":$status,"size":$body_bytes_sent,"ua":"$http_user_agent","rt":$request_time}';(注意:需确保字符串内无换行或未转义引号)location 块,在静态资源 location 中使用独立日志格式,避免混杂业务日志自定义日志容易因配置不当导致记录异常或性能下降:
log_format 后必须重载 Nginx(nginx -s reload),否则新格式不生效$request_time 写成 $request_timee)会导致该字段留空,但不会报错$http_* 类)可能轻微增加 CPU 开销,非必要不采集冗余字段