How to write only logs with 200 status
nginx 1.7.0+ allows using an if condition in access_log
directive itself.
access_log path [format [buffer=size [flush=time]] [if=condition]];The if parameter (1.7.0) enables conditional logging.A request will not be logged if the condition evaluates to “0” or an empty string
Combined with map
directive its possible to send log events to different logs based on various conditions.
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
you can do it by using ngx.log
and log_by_lua
directives.
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)'; }
In the above code, we use log_by_lua
which is called while running in log phase. In that if ngx.status == 200
, we use ngx.log to trigger the logging using ngx.log
.
This will write to error_log
. Not sure how to write it to access_log
.
For reference
In every question is a part of answer. You were very close:
if ($status != "200") { access_log off;}
Check info for version availability here.http://nginx.org/en/docs/http/ngx_http_core_module.html#variables
Also, almost all access log format vars are available in "modern" versions:http://nginx.org/en/docs/http/ngx_http_log_module.html