一、定义请求体变量:resp_body
二、引用lua文件:get_body.lua
三、日志格式中添加变量:resp_body
get_body.lua内容如下:
ngx.req.read_body()
local data = ngx.req.get_body_data()
if data ~= nil then
ngx.var.resp_body = data:sub(1,1000)
end
ngx.req.read_body() # 请求体尚未被读取前,需先调用这句
local data = ngx.req.get_body_data() # 读取请求体
ngx.var.resp_body = data:sub(1,1000) # 控制请求体长度
日志格式:
log_format main escape=json '{"timestamp_cn":"$time_iso8601",'
'"host":"$server_addr",'
'"clientip":"$remote_addr",'
'"args":"$args",'
'"status":"$status",'
'"method": "$request_method",'
'"bytes":"$body_bytes_sent",'
'"request_time":$request_time,'
'"upstreamtime":"$upstream_response_time",'
'"http_host":"$host",'
'"url":"$request_uri",'
'"uri":"$uri",'
'"referer":"$http_referer",'
'"content_type":"$content_type",'
'"uuid":"$http_uuid",'
'"lan":"$http_lan",'
'"ua":"$http_user_agent",'
'"app_version":"$http_app_version",'
'"device_type":"$http_device_type",'
'"isWifi":"$http_isWifi",'
'"memberId":"$http_memberId",'
'"device_id":"$http_device_id",'
'"upstream_cache_status":"$upstream_cache_status",'
'"request_body":"$resp_body"}';
# 注意:如果不添加escape=json,request_body会显示成十六进制,会影响将日志通过logstash采集到ES
日志结果: