在 Nginx 中,日志格式是通过 log_format 指令来定义的,然后在 access_log 指令中引用该格式。
下面给你一个从基础到常用的完整说明。
日志格式一般配置在 http 块中(全局生效):
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;
}
log_format:定义日志格式main:格式名称(可自定义)access_log:指定日志文件和使用的格式| 变量 | 含义 |
|---|---|
$remote_addr |
客户端 IP |
$remote_user |
认证用户(无则为 -) |
$time_local |
本地时间 |
$request |
请求行(方法 + URL + 协议) |
$status |
HTTP 状态码 |
$body_bytes_sent |
发送给客户端的字节数 |
$http_referer |
来源页面 |
$http_user_agent |
客户端浏览器/代理 |
$request_time |
请求总耗时(秒) |
$upstream_response_time |
后端响应时间 |
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent"';
log_format json escape=json '{'
'"time":"$time_local",'
'"remote_addr":"$remote_addr",'
'"request":"$request",'
'"status":$status,'
'"request_time":$request_time,'
'"upstream_time":"$upstream_response_time",'
'"ua":"$http_user_agent"'
'}';
使用:
access_log /var/log/nginx/access.log json;
✅ 适合 ELK / Loki / 日志采集
http {
log_format main '...';
log_format debug '...';
server {
access_log /var/log/nginx/access.log main;
access_log /var/log/nginx/debug.log debug;
}
}
错误日志不在 log_format 控制范围内:
error_log /var/log/nginx/error.log warn;
日志级别:
debug < info < notice < warn < error < crit < alert < emerg
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/example.log main;
location /api/ {
access_log /var/log/nginx/api.log json;
}
}
access_log off;
如果你有具体需求(比如 JSON 格式 / 统计 PV / 接入日志系统 / 性能分析),可以告诉我,我可以直接给你一份可用配置。