/

openresty配置request&respone输出到log

openresty配置request&respone输出到log

本机已安装openresty,并且配置正常访问。
需要openresty加载lua,然后把request和respone输出到日志里。
参考如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# 添加以下内容进入openresty的server_name具体监听的conf里
lua_need_request_body on;

set $resp_body "";
body_filter_by_lua '
local resp_body = string.sub(ngx.arg[1], 1, 1000)
ngx.ctx.buffered = (ngx.ctx.buffered or "") .. resp_body
if ngx.arg[2] then
ngx.var.resp_body = ngx.ctx.buffered
end
';

set $req_header "";
set $resp_header "";
header_filter_by_lua '
local h = ngx.req.get_headers()
for k, v in pairs(h) do
ngx.var.req_header = ngx.var.req_header .. k.."="..v.." "
end
local rh = ngx.resp.get_headers()
for k, v in pairs(rh) do
ngx.var.resp_header = ngx.var.resp_header .. k.."="..v.." "
end
';

修改openresty主文件的nginx.conf配置文件,修改log格式配置

1
2
3
log_format log_req_resp escape=json  '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" $request_time req_header:"$req_header" req_body:"$request_body" resp_header:"$resp_header" resp_body:"$resp_body"';

修改完成后执行测试,并且重启生效

1
2
openresty -t
openresty -s reload

参考链接:
Logging request & response body and headers with nginx
Is it possible to log the response data in nginx access log?
```