背景

一些场景下,我们并不需要记录 nginx 所有的 2xx 日志。 但需记录所有 4xx、5xx。 网上搜索到的方案,要么不记录 2xx,要么采样所有日志,都不满足需求。 下面我们使用 ngx_lua 来达成这样的目标:

  1. 对于 1xx、2xx、3xx,按照一定的百分比采样
  2. 对于 4xx、5xx,100% 的记录

直接上代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
lua_shared_dict c 1m;
init_by_lua_block {
    ngx.shared.c:add("countme", 0)
}

server {
    listen 8888;

    location /logme {
        set $logcon 1;
        log_by_lua_block {
            local c = ngx.shared.c
            c:incr("countme", 1)

            local ks = 10 -- keep 1/10

            if (ngx.status/100 < 4 and c:get("countme")%ks ~= 0)
            then
                ngx.var.logcon = 0
            end
        }

        access_log  /tmp/access.log main if=$logcon;
        error_log  /tmp/error.log;

        return 200;
        #return 400;
    }
}

上面代码中,ks = 10,代表只记录 10% 的日志。 测试过程就不写了,大家自己写个循环看下效果吧 :)

玩得开心 :)

-EOF-