# 日志配置
access_log
定义日志级别,日志位置。
日志级别:
debug > info > notice > warn > error > crit > alert > emerg
语法格式:
access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
access_log off;
默认值:
access_log logs/access.log combined;
作用域:
http, server, location, if in location, limit_except
配置样例:
access_log /spool/logs/nginx-access.log compression buffer=32k; |
# 日志格式
log_format
定义日志格式。
语法格式:
log_format name [escape=default|json] string ...;
默认值:
log_format combined "...";
作用域:
http
配置样例:
log_format compression '$remote_addr - $remote_user [$time_local] ' | |
'"$request" $status $bytes_sent ' | |
'"$http_referer" "$http_user_agent" "$gzip_ratio"'; | |
access_log /spool/logs/nginx-access.log compression buffer=32k; |
常见日志参数:
变量名 | 描述 |
---|---|
$remote_addr | 客户端的 IP 地址 |
$remote_user | 客户端请求中的用户 |
$time_local | 本地时间,格式为 [day/month/year:hour:minute:second zone] |
$request | 客户端请求的内容,包括 HTTP 方法、URI 和协议 |
$status | HTTP 响应的状态码 |
$body_bytes_sent | 发送给客户端的响应体的字节数 |
$http_referer | 客户端请求的来源页面的 URL |
$http_user_agent | 客户端的用户代理字符串 |
$http_x_forwarded_for | 客户端的原始 IP 地址,如果使用了代理服务器 |
$request_time | 服务器处理请求的时间,以秒为单位 |
$upstream_response_time | 后端服务器响应请求的时间,如果使用了代理服务器 |
$host | 请求的主机名 |
$server_name | 服务器名称 |
$request_uri | 客户端请求的 URI |
$http_cookie | 客户端请求中的 Cookie |
$http_host | 客户端请求的主机头 |
$http_accept_language | 客户端的语言偏好 |
$http_accept_encoding | 客户端支持的压缩算法 |
$http_connection | 客户端请求的连接类型 |
记录指定 URL 日志:
log_format sldn_log_format '$time_local - $remote_addr - $request_method $request_uri - $status'; | |
location /secret/ { | |
access_log sldn_secret_$time_local.txt sldn_log_format; | |
proxy_pass http://127.0.0.1:8080/; | |
} |
# 日志缓存
open_log_file_cache
设置日志文件缓存,提高日志文件访问性能。
语法格式: | |
open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time]; | |
open_log_file_cache off; | |
默认值: | |
open_log_file_cache off; | |
作用域: | |
http, server, location |
可选参数:max=N
:指定缓存的最大文件数。N 为一个正整数,表示最大文件数。inactive=time
:指定缓存文件的过期时间。time 为一个时间段,可以是一个数字加上一个时间单位(如 s、m、h、d),表示多少秒、分钟、小时或天。如果一个缓存文件在指定的时间段内没有被访问,则被认为是过期的。min_uses
:设置在 inactive 时间段内,日志文件最少使用多少次后,该日志文件描述符记入缓存中,默认是 1 次。valid
:设置检查频率,默认 60s。
配置样例:
open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2; |