Nginx:登录多个条件

时间:2017-06-13 11:57:33

标签: 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;
          [..]
     }
}

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

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,但不记录此。

1 个答案:

答案 0 :(得分:2)

您可以使用多个map指令和前一个块的默认值。例如,log 4xx状态请求,其中User-Agent不包含" AppleWebKit"

map $status $loggable_status {
    ~^[4]   1;
    default 0;
}
map $http_user_agent $loggable_user_agent {
    ~*AppleWebKit   0;
    default $loggable_status;
}
access_log /var/log/nginx/error.log combined if=$loggable_user_agent;