在 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 |
客户端浏览器 |
$request_time |
请求总耗时(秒) |
$upstream_response_time |
后端响应时间 |
$host |
请求的 Host |
$server_name |
匹配的 server 名称 |
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
log_format timing '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'$request_time $upstream_response_time '
'"$http_referer" "$http_user_agent"';
log_format json escape=json '{'
'"time":"$time_iso8601",'
'"remote_addr":"$remote_addr",'
'"request":"$request",'
'"status":$status,'
'"body_bytes_sent":$body_bytes_sent,'
'"request_time":$request_time,'
'"upstream_time":"$upstream_response_time",'
'"http_user_agent":"$http_user_agent"'
'}';
使用:
access_log /var/log/nginx/access.log json;
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/example.access.log main;
}
error_log /var/log/nginx/error.log warn;
日志级别:
debug | info | notice | warn | error | crit | alert | emerg
nginx -t
nginx -s reload
buffer:access_log /var/log/nginx/access.log main buffer=32k flush=5s;
如果你有 特定分析需求(如统计接口耗时、用户行为、安全审计),可以告诉我,我帮你定制日志格式。