Nginx:登录多个条件

标签 nginx logging conditional

我正在尝试使用条件 access_logging 配置 nginx/1.13.0。

如果 access_logging 仅以 $status 代码为条件,则一切正常:

http {
     [..]
     map $status $logworthy_status {
         ~^[4]  1;
         default 0;
     }
     [..]
     server {
          [..]
          access_log  /var/log/nginx_access.log combined if=$logworthy_status;
          [..]
     }
}

调试日志显示 map 的行为符合预期:

2017/06/13 11:34:14 [debug] 23153#0: *203 http map started
2017/06/13 11:34:14 [debug] 23153#0: *203 http script var: "401"
2017/06/13 11:34:14 [debug] 23153#0: *203 http map: "401" "1"

但是,如果我尝试重写它以允许多个条件,如建议 here :

http {
     [..]
     map $status $logworthy_status {
         ~^[4]  1;
         default 0;
     }
     [..]
     server {
          [..]
          set $logworthy 0;
          if ( $logworthy_status = 1 ) {
              set $logworthy 1;
          }
          access_log  /var/log/nginx_access.log  combined if=$logworthy;
          [..]
     }
}

不生成日志消息。检查调试日志显示,即使是 $status 上的映射似乎也搞砸了:

2017/06/13 11:38:12 [debug] 23631#0: *204 rewrite phase: 0
2017/06/13 11:38:12 [debug] 23631#0: *204 http script value: "0"
2017/06/13 11:38:12 [debug] 23631#0: *204 http script set $logworthy
2017/06/13 11:38:12 [debug] 23631#0: *204 http script var
2017/06/13 11:38:12 [debug] 23631#0: *204 http map started
2017/06/13 11:38:12 [debug] 23631#0: *204 http script var: "000"
2017/06/13 11:38:12 [debug] 23631#0: *204 http map: "000" "0"
2017/06/13 11:38:12 [debug] 23631#0: *204 http script var: "0"
2017/06/13 11:38:12 [debug] 23631#0: *204 http script value: "1"
2017/06/13 11:38:12 [debug] 23631#0: *204 http script equal
2017/06/13 11:38:12 [debug] 23631#0: *204 http script equal: no
2017/06/13 11:38:12 [debug] 23631#0: *204 http script if
2017/06/13 11:38:12 [debug] 23631#0: *204 http script if: false

有人可以解释一下吗?请求按预期处理,nginx 返回 401,但没有记录。

最佳答案

您可以使用多个 map具有来自前一个 block 的默认值的指令。例如,记录 4xx 状态请求,其中 User-Agent 不包含“AppleWebKit”

map $status $loggable_status {
    ~^[4]   1;
    default 0;
}
map $http_user_agent $loggable_user_agent {
    ~*AppleWebKit   0;
    default $loggable_status; # Use map var above as default
}

access_log /var/log/nginx/error.log combined if=$loggable_user_agent;

关于Nginx:登录多个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44520875/

相关文章:

.net - 为什么 .NET 的条件属性会导致副作用被删除?

条件组件声明和以下 if 等式

css - NGINX 无法加载 css

ubuntu - 我使用 nginx 创建了虚拟主机,但收到 403 Forbidden

ruby-on-rails - 使用 Rails 4 和结构化日志记录,如何将请求 ID 字段添加到日志中?

c++ - Boost::log 在初始化后立即停止记录

python - 在 ubuntu 16.04 上使用 nginx、uwsgi python-flask 获取 "502 Bad Gateway"

python - AWS EC2 免费层 Django 应用程序

java - Log4j-2.6.2 基本配置器未配置日志记录级别

python - 条件 If 语句 : If value in row contains string . .. 设置另一列等于字符串