nginx收集request_body、response_body
  tdJcRsFnVfPo 2023年11月02日 37 0

1、收集request_body:

对于get请求,request_body始终是空,对于post请求,request_body是参数信息。request_body的获取有两种方式:

  • 使用nginx ngx_http_core模块的$request_body;
  • openresty中使用lua脚本。
# 首先修改配置文件,我这里采集的日志只有request_body字段
vim /opt/nginx/conf/nginx.conf
log_format main $request_body;

access_log logs/access.log main;

location / {
root /opt/nginx/html;
# 以下为添加内容
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}

使用post发送数据,就可以在nginx日志中查看到请求参数了。

curl -XPOST "http://10.10.10.13/test.php?id=123" -H "X-Forwarded-For: 10.10.10.5" -H "Referer: http://10.10.10.13" --data "AAAAAAAAAAAAAAAAAA"

使用ngx_http_core模块收集日志有没有办法限制request_body的长度呢?

1)可以在配置文件中使用client_max_body_size 1k; 但是这个配置是不允许用户上传超过1K大小的body内容,如果用户需要上传图片,业务可能就无法正常运行,所以不推荐使用此种方法。

2)使用lua:

vim /opt/nginx/conf/nginx.conf
log_format main $request_body_head;

access_log logs/access.log main;

location / {
root /opt/nginx/html;
# 以下为添加内容
set $request_body_head "";
content_by_lua_block {
ngx.req.read_body()
local req_body = ngx.req.get_body_data()
# 这里的1000代表我们截取request_body的长度,不要取的太长,否则容易导致日志过大
ngx.var.request_body_head = req_body:sub(1,1000)
}
}

2、收集response_body:

对于response_body我们只有使用lua编写脚本来采集。

server {
listen 80;
server_name localhost;
# 以下为添加内容
lua_need_request_body on;
set $response_body "";
body_filter_by_lua '
# 这里的1000就代表截取response_body的长度,不要取的太长,否则容易导致日志过大
local response_body = string.sub(ngx.arg[1],1,1000)
ngx.ctx.buffered = (ngx.ctx.buffered or "") .. response_body
if ngx.arg[2] then
ngx.var.response_body = ngx.ctx.buffered
end
';
}

3、日志json格式化;

http {
include mime.types;
default_type application/octet-stream;
log_format main escape=json '{'
'"timestamp": $time_local '
'"remote_addr": $remote_addr '
'"remote_user": "$remote_user '
'"request_method": $request_method '
'"request_uri": "$request_uri" '
'"request_protocol": "$server_protocol" '
'"request_length": $request_length '
'"request_time": $request_time '
'"request_body_head": "$request_body_head" '
'"response_status": $status '
'"body_bytes_sent": $body_bytes_sent '
'"bytes_sent": $bytes_sent '
'"response_body": "$response_body" '
'"http_referer": "$http_referer" '
'"http_user_agent": "$http_user_agent" '
'"http_x_forwarded_for": "$http_x_forwarded_for" '
'"http_host": "$http_host" '
'"server_name": "$server_name" '
'"upstream_addr": "$upstream_addr" '
'"upstream_status": $upstream_status'
'}';

access_log logs/access.log main;

​https://zhuanlan.zhihu.com/p/100080719​​  


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

tdJcRsFnVfPo