如何仅记录状态为200的日志

我正在尝试解决以下问题:

  1. 请求进来了。

  2. HttpLuaModule 对请求执行某些操作。如果请求有效,则 Lua 会使用 ngx.exit(202) 完成处理。但是,在处理过程中可能会出现(并且会)一些条件,并且 nginx 可能会返回 403、404、503 错误。

我想做的是只记录具有 200 状态代码的请求的访问日志。 基本上,我想做的是这样的:

location /foo {
    content_by_lua_file "/opt/nginx/lua/process.lua";
    if (status == 200) {
        access_log "/path/to/the/access_log"
    }

我对 nginx 和 lua 都非常陌生,所以对我来说,找出该在哪里放置 if 语句(在 content_by_lua_file 后面或在 lua 文件中)以及这个 if 语句应该长什么样子是一件挑战。

点赞
用户1548504
用户1548504

你可以通过使用 ngx.loglog_by_lua 指令来实现。

location /conditional_log{
        log_by_lua 'if ngx.status == 200 then ngx.log(ngx.ERR, "It is 200") end';
        content_by_lua 'ngx.say("I am ok") ngx.exit(200)';
    }

在上面的代码中,我们使用了 log_by_lua,它在运行日志阶段时被调用。如果 ngx.status == 200,那么我们使用 ngx.log 触发日志记录。

这将写入 error_log。不确定如何编写到 access_log

参考链接:

http://wiki.nginx.org/HttpLuaModule#ngx.log

http://wiki.nginx.org/HttpLuaModule#log_by_lua

2013-09-26 13:40:04
用户1516286
用户1516286

下面是我想出的解决方案:

auth.lua

-- 在这里添加一些逻辑
-- ....
-- ....
ngx.var.return_status = 200

nginx.conf

http {
   lua_package_path .....;
   lua_package_cpath ....;

   rewrite_by_lua_no_postpone on;

   server {

     set $return_status 1;

     location /foo {
        rewrite_by_lua_file "<apth_to_aut.lua";

        if ($return_status = 200) {
            access_log  <path_to_access_log>  format;
            return 200;
        }
     }
   }
}
2013-09-27 12:38:16
用户121048
用户121048

每个问题中都包含答案的一部分。你很接近了:

if ($status != "200") {
    access_log off;
}

请查看此处版本可用性的信息。 http://nginx.org/en/docs/http/ngx_http_core_module.html#variables

此外,几乎所有访问日志格式变量都可以在“现代”版本中使用: http://nginx.org/en/docs/http/ngx_http_log_module.html

2014-01-27 15:15:56
用户2208271
用户2208271

nginx 1.7.0+允许在 access_log 指令本身中使用 if 条件。

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

if 参数(1.7.0)允许有条件地记录日志。
如果条件计算结果为“0”或空字符串,则不会记录请求。

结合 map 指令,可以基于不同条件将日志事件发送到不同的日志中。

http {

    map $status $normal {
        ~^2  1;
        default 0;
    }
    map $status $abnormal {
        ~^2  0;
        default 1;
    }
    map $remote_addr $islocal {
        ~^127  1;
        default 0;
    }

    server {

        access_log logs/access.log combined if=$normal;
        access_log logs/access_abnormal.log combined if=$abnormal;
        access_log logs/access_local.log combined if=$islocal;

    }
}

http://nginx.org/en/docs/http/ngx_http_log_module.html

http://nginx.org/en/docs/http/ngx_http_map_module.html

2014-09-15 16:26:22