Nginx 的日志格式通过 log_format 指令定义,再在 access_log 指令中引用。下面按常见用法说明。
通常在 http 块中定义日志格式,在 server 或 location 中指定使用哪种日志。
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 |
访问时间 |
$request |
请求行(方法 URL 协议) |
$status |
HTTP 状态码 |
$body_bytes_sent |
发送字节数 |
$http_referer |
来源页 |
$http_user_agent |
客户端 UA |
$request_time |
请求总耗时(秒) |
$upstream_response_time |
后端响应时间 |
$host |
请求 Host |
$request_method |
请求方法 |
方便 ELK / Loki 等日志系统解析:
log_format json_log escape=json '{
"time": "$time_iso8601",
"remote_addr": "$remote_addr",
"request": "$request",
"status": $status,
"body_bytes": $body_bytes_sent,
"request_time": $request_time,
"upstream_time": "$upstream_response_time",
"user_agent": "$http_user_agent"
}';
access_log /var/log/nginx/access.json.log json_log;
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/example.log main;
}
access_log off;
log_format 只能在 http 块中定义nginx -s reloadescape=json 防止日志注入问题如果你有 具体场景(如:统计接口耗时、按用户 ID 记录、Docker / K8s 日志),我可以给你更合适的格式。