如何仅记录状态为200的日志
2013-9-25 17:43:54
收藏:0
阅读:113
评论:4
我正在尝试解决以下问题:
请求进来了。
HttpLuaModule对请求执行某些操作。如果请求有效,则 Lua 会使用ngx.exit(202)完成处理。但是,在处理过程中可能会出现(并且会)一些条件,并且nginx可能会返回 403、404、503 错误。
我想做的是只记录具有 200 状态代码的请求的访问日志。 基本上,我想做的是这样的:
location /foo {
content_by_lua_file "/opt/nginx/lua/process.lua";
if (status == 200) {
access_log "/path/to/the/access_log"
}
我对 nginx 和 lua 都非常陌生,所以对我来说,找出该在哪里放置 if 语句(在 content_by_lua_file 后面或在 lua 文件中)以及这个 if 语句应该长什么样子是一件挑战。
点赞
用户1516286
下面是我想出的解决方案:
auth.lua
-- 在这里添加一些逻辑
-- ....
-- ....
ngx.var.return_status = 200
nginx.conf
http {
lua_package_path .....;
lua_package_cpath ....;
rewrite_by_lua_no_postpone on;
server {
set $return_status 1;
location /foo {
rewrite_by_lua_file "<apth_to_aut.lua";
if ($return_status = 200) {
access_log <path_to_access_log> format;
return 200;
}
}
}
}
2013-09-27 12:38:16
用户121048
每个问题中都包含答案的一部分。你很接近了:
if ($status != "200") {
access_log off;
}
请查看此处版本可用性的信息。 http://nginx.org/en/docs/http/ngx_http_core_module.html#variables
此外,几乎所有访问日志格式变量都可以在“现代”版本中使用: http://nginx.org/en/docs/http/ngx_http_log_module.html
2014-01-27 15:15:56
用户2208271
nginx 1.7.0+允许在 access_log 指令本身中使用 if 条件。
access_log path [format [buffer=size [flush=time]] [if=condition]];
if 参数(1.7.0)允许有条件地记录日志。
如果条件计算结果为“0”或空字符串,则不会记录请求。
结合 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;
}
}
2014-09-15 16:26:22
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
你可以通过使用
ngx.log和log_by_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)'; }在上面的代码中,我们使用了
log_by_lua,它在运行日志阶段时被调用。如果ngx.status == 200,那么我们使用ngx.log触发日志记录。这将写入
error_log。不确定如何编写到access_log。参考链接:
http://wiki.nginx.org/HttpLuaModule#ngx.log
http://wiki.nginx.org/HttpLuaModule#log_by_lua