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/
log_format main $request_body;
access_log logs/ main;
location / {
root /opt/nginx/html;
# 以下为添加内容
fastcgi_pass 127.0.0.1:9000;
fastcgi_index ;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
使用post发送数据,就可以在nginx日志中查看到请求参数了。
curl -XPOST "http://10.10.10.13/?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/
log_format main $request_body_head;
access_log logs/ main;
location / {
root /opt/nginx/html;
# 以下为添加内容
set $request_body_head "";
content_by_lua_block {
.read_body()
local req_body = .get_body_data()
# 这里的1000代表我们截取request_body的长度,不要取的太长,否则容易导致日志过大
.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 = ([1],1,1000)
= ( or "") .. response_body
if [2] then
.response_body =
end
';
}
3、日志json格式化;
http {
include ;
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/ main;
/p/100080719