Nginx 如何仅写入状态为200的日志
我正试图找出如何执行以下操作:Nginx 如何仅写入状态为200的日志,nginx,lua,http-status-codes,Nginx,Lua,Http Status Codes,我正试图找出如何执行以下操作: 请求进来了 HttpLuaModule对请求执行一些操作。如果请求有效,Lua将使用ngx.exit(202)完成处理。但是,在处理过程中可能(也将)出现一些情况,nginx可能返回403404503个错误 我想做的是只向access日志写入状态代码为200的请求。 基本上我想这样做: location /foo { content_by_lua_file "/opt/nginx/lua/process.lua"; if (status == 20
HttpLuaModule
对请求执行一些操作。如果请求有效,Lua将使用ngx.exit(202)
完成处理。但是,在处理过程中可能(也将)出现一些情况,nginx
可能返回403404503个错误location /foo {
content_by_lua_file "/opt/nginx/lua/process.lua";
if (status == 200) {
access_log "/path/to/the/access_log"
}
我对nginx和lua都很陌生,所以对我来说,弄清楚在哪里放置和if语句(通过lua\u文件在
content\u之后或在side lua文件中)以及if语句应该是什么样子是一个挑战。可以使用ngx.log
和log\u by\u 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)';
}
在上面的代码中,我们使用在日志阶段运行时调用的logbylua
。在这种情况下,如果ngx.status==200
,我们使用ngx.log触发使用ngx.log
的日志记录
这将写入错误日志
。不确定如何将其写入access\u log
供参考
这是我提出的解决方案:
auth.lua
nginx.conf
http{
lua_包_路径。。。。。;
lua_包_cpath。。。。;
由卢奥改写,不推迟;
服务器{
设置$return\u状态1;
地点/食物{
重写文件“每个问题都是答案的一部分。你非常接近:
if ($status != "200") {
access_log off;
}
请在此处查看有关版本可用性的信息。
此外,几乎所有访问日志格式变量都有“现代”版本:
nginx 1.7.0+允许在access\u log
指令本身中使用if条件
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
结合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;
}
}
谢谢你的回答,但我真的很想写访问日志,我想出了一个非常复杂的解决方案:设置一个全局变量foo
,然后将content\u by_lua
更改为rewrite\u by_lua
,最后如果一切正常,我将variblefoo
更改为200。然后在脚本之后,我有一个类似的if stat我在问题中发布的ement。希望有人能提出更优雅的建议。这很好。它回答了我关于条件日志的一个稍微不同的问题。
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
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;
}
}