插件窝 干货文章 nginx的access_log格式怎么设置

nginx的access_log格式怎么设置

Nginx Log Access time 438    来源:    2025-04-27

Nginx Access Log 格式设置指南

Nginx的access_log用于记录客户端请求的访问信息,可以通过自定义格式来收集所需的访问数据。以下是详细的设置方法:

基本语法

access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];

预定义格式

Nginx有几个预定义的日志格式:

  1. combined (最常用,类似Apache的combined格式)
  2. main (基本格式)

自定义日志格式

使用log_format指令定义自定义格式:

log_format custom_format '$remote_addr - $remote_user [$time_local] '
                         '"$request" $status $body_bytes_sent '
                         '"$http_referer" "$http_user_agent" "$http_x_forwarded_for"';

然后在server或location块中使用:

access_log /var/log/nginx/access.log custom_format;

常用变量

变量 说明
$remote_addr 客户端IP地址
$remote_user 客户端用户名(基本认证)
$time_local 本地时间
$request 完整的原始请求行
$status 响应状态码
$body_bytes_sent 发送给客户端的字节数
$http_referer 请求来源页地址
$http_user_agent 客户端浏览器信息
$http_x_forwarded_for 代理服务器IP
$request_time 请求处理时间(秒)
$upstream_response_time 上游服务器响应时间
$bytes_sent 发送给客户端的字节总数
$connection 连接序列号
$connection_requests 当前连接上的请求数

高级示例

JSON格式日志

log_format json_log escape=json
  '{'
    '"time_local":"$time_local",'
    '"remote_addr":"$remote_addr",'
    '"remote_user":"$remote_user",'
    '"request":"$request",'
    '"status": "$status",'
    '"body_bytes_sent":"$body_bytes_sent",'
    '"request_time":"$request_time",'
    '"http_referrer":"$http_referer",'
    '"http_user_agent":"$http_user_agent"'
  '}';

access_log /var/log/nginx/access.json json_log;

包含更多信息的日志

log_format detailed '$remote_addr - $remote_user [$time_local] '
                   '"$request" $status $body_bytes_sent '
                   '"$http_referer" "$http_user_agent" '
                   'rt=$request_time uct="$upstream_connect_time" uht="$upstream_header_time" urt="$upstream_response_time"';

access_log /var/log/nginx/access.log detailed;

性能优化选项

access_log /var/log/nginx/access.log combined buffer=32k gzip flush=5m;
  • buffer:设置缓冲区大小
  • gzip:启用日志压缩
  • flush:设置缓冲区刷新时间

条件日志记录

map $status $loggable {
    ~^[23]  0;  # 不记录2xx和3xx状态
    default 1;  # 记录其他状态
}

access_log /var/log/nginx/access.log combined if=$loggable;

注意事项

  1. 修改配置后需要重载Nginx:nginx -s reload
  2. 日志文件需要Nginx进程有写入权限
  3. 对于高流量网站,考虑日志轮转(logrotate)
  4. JSON格式日志需要Nginx 1.11.8+版本支持escape=json参数

希望这些信息对您设置Nginx访问日志有所帮助!