I want to keep track of the HTTP-response-codes my application generates. Therefore I want to use an existing redis db connected via unix domain socket. I know that the cosocket API is not available in the log_by_lua directive so I tried the workaround with using ngx.timer.at. If my understanding is correct, I can use cosocket API (and therefore the lua_resty_redis module) cause its not running in log_by_lua but in a separate context of the ligth thread. Somehow I still get error messages saying that the cosocket API is not available in log_by_lua so it seems to me either I'm doing something wrong here or the implementation has changed and the workaround is not working anymore.
Here is my code:
`
log_by_lua_block{
local function update_stats(premature, request_method, status, ip_addr)
local redis = require "resty.redis"
local red = redis:new()
local ok, err = red:connect("unix:/run/redis.sock")
if not ok then
ngx.log(ngx.ERROR, "failed to connect: ", err)
return
end
if status == 200 then
ok, err = red:incr(ip_addr.."_200_reqs")
elseif status == 404 then
ok, err = red:incr(ip_addr.."_404_reqs")
...
end
if request_method == "GET" then
ok, err = red:incr(ip_addr.."_GET_reqs")
else ...
end
red:set_keepalive(1000,100)
end
ngx.timer.at(0, update_stats(ngx.var.request_method, ngx.status, ngx.var.remote_addr))
`
Here is my error message
2021/12/20 19:12:12 [error] 312315#0: *21815 failed to run log_by_lua*: /usr/local/openresty/lualib/resty/redis.lua:63: API disabled in the context of log_by_lua*
stack traceback:
[C]: in function 'tcp'
/usr/local/openresty/lualib/resty/redis.lua:63: in function 'new'
log_by_lua(nginx.conf:141):12: in function 'update_stats'
log_by_lua(nginx.conf:141):51: in main chunk while logging request, client: 127.0.0.1, server: localhost, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:4444/", host: "localhost"
Thanks
P.S. I also tried moving the update_stats function to a separate module but I'm still getting the same error