仅记录 4xx 和 5xx 日志 access_log - Nginx 1.5.12.1

Logging only 4xx and 5xx logs in access_log - Nginx 1.5.12.1

我有 nginx 版本:openresty/1.5.12.1.

有没有办法只将 4xx 和 5xx 日志记录到 access_log 或另一个 access_log 文件?

我的意思是,这些日志应该在默认的 access_log 文件中。此外,它们也应该记录在自定义日志文件中。 只记录 4xx 和 5xx 也不错。

谢谢!

如果不编辑源代码或编写 Nginx 第 3 方模块,他们无法做到这一点(据我所知和所见)。

为什么不只是 运行 通过 grep 之类的日志?

一个很棒的日志解析小教程,可能会对您有所帮助: https://rtcamp.com/tutorials/nginx/log-parsing/

grep "404" access.log | sed -e 's/.GET //' -e 's/\ .//'|排序 | uniq-c |排序-n | gawk '{print $2","$1}'

不,nginx 1 似乎不可能做到这一点。5.x。

是的,自 nginx 1.7.0 (http://nginx.org/en/docs/http/ngx_http_log_module.html#access_log) 起,可以在 nginx.conf 个文件中执行此操作:

来自 https://docs.nginx.com/nginx/admin-guide/monitoring/logging/#conditional :

map $status $loggable {
    ~^[23]  0;
    default 1;
}

access_log /path/to/access.log combined if=$loggable;

这将跳过记录所有 2xx 和 3xx 状态代码。您可以将其重写为正 select 4xx 和 5xx 状态代码(尽管这些在很大程度上是等效的,除非您返回大量 1xx 状态代码或返回 non-standard > 599 状态代码,这很奇怪) :

map $status $loggable {
    ~^[45]  1;
    default 0;
}

access_log /path/to/access.log combined if=$loggable;