Nginx访问日志(access_log)配置及信息详解

Nginx访问日志主要有两个参数控制:
log_format #用来定义记录日志的格式(可以定义多种日志格式,取不同名字即可)
access_log #用来指定日至文件的路径及使用的何种日志格式记录日志

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

access_log的默认值:

#access_log  logs/access.log  main;

log_format

log_format语法格式及参数语法说明如下:

 log_format    <NAME>    <Strin­­­g>;

    关键字     格式标签   日志格式

    关键字:其中关键字error_log不能改变
    格式标签:格式标签是给一套日志格式设置一个独特的名字
    日志格式:给日志设置格式
    
作用域    :    http

eg:

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;

log_format格式变量:

参数                      说明                                         示例
$remote_addr             客户端地址                                    211.28.65.253
$remote_user             客户端用户名称                                --
$time_local              访问时间和时区                                18/Jul/2012:17:00:01 +0800
$request                 请求的URI和HTTP协议                           "GET /article-10000.html HTTP/1.1"
$http_host               请求地址,即浏览器中你输入的地址(IP或域名)     www.wang.com 192.168.100.100
$status                  HTTP请求状态                                  200
$upstream_status         upstream状态                                  200
$body_bytes_sent         发送给客户端文件内容大小                        1547
$http_referer            url跳转来源                                   https://www.baidu.com/
$http_user_agent         用户终端浏览器等信息                           "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SV1; GTB7.0; .NET4.0C;
$ssl_protocol            SSL协议版本                                   TLSv1
$ssl_cipher              交换数据中的算法                               RC4-SHA
$upstream_addr           后台upstream的地址,即真正提供服务的主机地址     10.10.10.100:80
$request_time            整个请求的总时间                               0.205
$upstream_response_time  请求过程中,upstream响应时间                    0.002

access_log

语法格式及参数语法说明如下:

    access_log    <FILE>    <NAME>;
    关键字         日志文件   格式标签


    关键字:其中关键字error_log不能改变
    日志文件:可以指定任意存放日志的目录
    格式标签:给日志文件套用指定的日志格式


其他语法:

    access_log    off;  #关闭access_log,即不记录访问日志
    access_log path [format [buffer=size [flush=time]] [if=condition]];
    access_log path format gzip[=level] [buffer=size] [flush=time] [if=condition];
    access_log syslog:server=address[,parameter=value] [format [if=condition]];

    说明:
    buffer=size  #为存放访问日志的缓冲区大小
    flush=time  #为缓冲区的日志刷到磁盘的时间
    gzip[=level]  #表示压缩级别
    [if = condition]  #表示其他条件
    
作用域(参数的标签段位置)   : http, server, location, if in location, limit_except

eg:

access_log /spool/logs/nginx-access.log compression buffer=32k;

open_log_file_cache

使用open_log_file_cache来设置日志文件缓存(默认是off)。

max:设置缓存中的最大文件描述符数量,如果缓存被占满,采用LRU算法将描述符关闭。
inactive:设置存活时间,默认是10s
min_uses:设置在inactive时间段内,日志文件最少使用多少次后,该日志文件描述符记入缓存中,默认是1次
valid:设置检查频率,默认60s
off:禁用缓存

语法格式:   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

eg:

open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2;

参考资料:http://nginx.org/en/docs/http/ngx_http_log_module.html

nginx日志调试技巧

设置 Nginx 仅记录来自于你的 IP 的错误

当你设置日志级别成 debug,如果你在调试一个在线的高流量网站的话,你的错误日志可能会记录每个请求的很多消息,这样会变得毫无意义。

在events{…}中配置如下内容,可以使 Nginx 记录仅仅来自于你的 IP 的错误日志。

events {
        debug_connection 1.2.3.4;
}

调试 nginx rewrite 规则

调试rewrite规则时,如果规则写错只会看见一个404页面,可以在配置文件中开启nginx rewrite日志,进行调试。

server {
        error_log    /var/logs/nginx/example.com.error.log;
        rewrite_log on;
}

rewrite_log on; 开启后,它将发送所有的 rewrite 相关的日志信息到 error_log 文件中,使用 [notice] 级别。随后就可以在error_log 查看rewrite信息了。

使用location记录指定URL的日志

server {
        error_log    /var/logs/nginx/example.com.error.log;
        location /static/ { 
        error_log /var/logs/nginx/static-error.log debug; 
    }         
}

Nginx配置访问日志过程:

(1)创建log_format语句

worker_processes  1;
error_log logs/error.log error;
events {
    worker_connections  1024;
}
http {
    include status.conf;
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                               '$status $body_bytes_sent "$http_referer" '
                               '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  logs/access.log  main;
    server {
        listen       80;
        server_name  localhost;
                rewrite ^/.* http://www.wl.com permanent;
    }
    include vhost/*.conf;
}

(2)插入access_log语句

server {
        access_log /data/log/www;
        listen 80;
        server_name abc.com www.wl.com;

        location / {
                root /data/www/www;
                index index.html index.htm;
        }
        error_log    logs/error_www.wl.com.log    error;
        access_log    logs/access_www.wl.com.log    main;
        #新增内容↑

}

(3)重启服务

nginx -t
nginx -s reload

常用例子

main格式

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"'
                       '$upstream_addr $upstream_response_time $request_time ';
access_log  logs/access.log  main;

json格式

log_format logstash_json '{"@timestamp":"$time_iso8601",'
       '"host": "$server_addr",'
       '"client": "$remote_addr",'
       '"size": $body_bytes_sent,'
       '"responsetime": $request_time,'
       '"domain": "$host",'
       '"url":"$request_uri",'
       '"referer": "$http_referer",'
       '"agent": "$http_user_agent",'
       '"status":"$status",'
       '"x_forwarded_for":"$http_x_forwarded_for"}';

解释:
u r i 请 求 中 的 当 前 U R I ( 不 带 请 求 参 数 , 参 数 位 于 uri 请求中的当前URI(不带请求参数,参数位于 uriURI(args),不同于浏览器传递的$request_uri的值,它可以通过内部重定向,或者使用index指令进行修改。不包括协议和主机名,例如/foo/bar.html。
r e q u e s t u r i 这 个 变 量 等 于 包 含 一 些 客 户 端 请 求 参 数 的 原 始 U R I , 它 无 法 修 改 , 请 查 看 request_uri 这个变量等于包含一些客户端请求参数的原始URI,它无法修改,请查看 requesturiURIuri更改或重写URI。
也就是说: r e q u e s t u r i 是 原 始 请 求 U R L , request_uri是原始请求URL, requesturiURLuri则是经过nginx处理请求后剔除参数的URL,所以会将汉字表现为union。
坑点:
使用 u r i 可 以 在 n g i n x 对 U R L 进 行 更 改 或 重 写 , 但 是 用 于 日 志 输 出 可 以 使 用 uri 可以在nginx对URL进行更改或重写,但是用于日志输出可以使用 uringinxURL使request_uri代替,如无特殊业务需求,完全可以替换。

压缩格式

日志中增加了压缩的信息。

http {
    log_format compression '$remote_addr - $remote_user [$time_local] '
                           '"$request" $status $body_bytes_sent '
                           '"$http_referer" "$http_user_agent" "$gzip_ratio"';

    server {
        gzip on;
        access_log /spool/logs/nginx-access.log compression;
        ...
    }
}

upstream格式

增加upstream消耗的时间。

http {
    log_format upstream_time '$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"';

    server {
        access_log /spool/logs/nginx-access.log upstream_time;
        ...
    }
}

统计信息

统计status 出现的次数

awk '{print $9}' access.log | sort | uniq -c | sort -rn

36461 200 
483 500
87 404
9 400
3 302
1 499
1 403
1 301

显示返回302状态码的URL。

awk '($9 ~ /302/)' access.log | awk '{print $7}' | sort | uniq -c | sort -rn

1 /wp-login.php
1 /wp-admin/plugins.php?action=activate&plugin=ewww-image-optimizer%2Fewww-image-optimizer.php&_wpnonce=cc4a379131
1 /wp-admin/
<think>嗯,用户想了解Nginx配置文件中access_log指令的具体用法,还要求详细说明和配置示例。首先,我需要回忆一下access_log的基本作用,它是用来记录客户端请求的日志的。然后,我得考虑它的语法结构,比如路径、格式和条件这些参数。 接下来,用户可能需要知道如何配置不同的日志格式,比如使用main或者自定义格式。还要提到作用域,这个指令可以用在http、server、location块里,不同位置的配置会有优先级问题,这点很重要,不能搞错。 然后,配置示例部分应该给出几个常见场景,比如基本的访问日志、按天分割日志、条件记录和不同格式的日志。这些示例要具体,让用户能直接复制使用。另外,要提到日志分析工具,比如awk和GoAccess,这样用户知道如何处理生成的日志。 还要注意引用的问题,用户提供的几个引用链接中,引用[1]、[2]、[4]都涉及access_log配置和统计,需要正确对应到回答里。比如路径配置、按天分割的方法,这些在引用里都有提到,要确保信息准确。 可能用户没有明说但需要知道的是如何优化日志记录,比如关闭日志、按条件记录来减少磁盘IO,或者如何做日志轮转。这些高级用法可以作为补充内容,帮助用户更全面地应用access_log指令。 最后,生成的相关问题要围绕access_log展开,比如路径管理、格式自定义、日志分析、性能优化、按时间分割和权限相关的问题,这样能引导用户进一步深入学习。需要确保每个问题都有对应的知识点,并且引用正确的参考资料。</think>### Nginx access_log指令详解 #### 一、指令作用 access_log指令用于记录客户端请求的访问日志,包含请求时间、客户端IP、响应状态等关键信息,是进行流量分析、故障排查的基础工具[^1][^4]。 #### 二、指令语法 ```nginx access_log path [format [buffer=size] [gzip=level] [flush=time] [if=condition]]; ``` 或关闭日志记录: ```nginx access_log off; ``` - `path`:日志文件存储路径(支持变量) - `format`:指定日志格式(默认使用combined格式) - `buffer`:设置内存缓冲区大小 - `gzip`:启用日志压缩(1-9级压缩比) - `if`:条件记录 #### 三、作用范围 可配置于以下上下文: - http - server - location (注意:子块配置会覆盖父块配置) #### 四、配置示例 1. **基础配置** ```nginx http { log_format main '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent"'; server { access_log /var/log/nginx/access.log main; } } ``` 2. **按天分割日志** ```nginx server { access_log /var/log/nginx/access_$year-$month-$day.log main; # 需配合crontab定时任务进行日志切割[^4] } ``` 3. **条件记录** ```nginx # 仅记录4xx/5xx错误 map $status $loggable { ~^[23] 0; default 1; } server { access_log /var/log/nginx/errors.log main if=$loggable; } ``` 4. **缓冲写入** ```nginx access_log /var/log/nginx/access.log main buffer=32k gzip=5 flush=5m; ``` #### 五、日志分析 常用分析命令: ```bash # 统计访问量TOP10 awk '{print $7}' access.log | sort | uniq -c | sort -nr | head -n 10 # 使用GoAccess可视化分析 goaccess access.log -o report.html --log-format=COMBINED ``` #### 六、高级技巧 1.日志输出 ```nginx server { access_log /var/log/nginx/basic.log; access_log /var/log/nginx/debug.log debug_format; } ``` 2. 性能优化建议 - 生产环境建议保持buffer=64k - 高并发场景可设置`open_log_file_cache` - 调试完成后及时关闭debug日志
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

strggle_bin

一毛不嫌少,十元不嫌多

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值