欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Envoy打印请求和响应Body

程序员文章站 2024-03-14 11:18:46
...

1、添加Lua Filter实现对请求和响应的拦截

参考:https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_filters/lua_filter#dynamic-metadata-object-api

Envoy打印请求和响应Body

利用Lua脚本提取请求和响应Body信息,并设置到dynamicMetadata中。Lua脚本内容如下:

function envoy_on_request(request_handle)
  local request_body_buffer = request_handle:body()
  if(request_body_buffer == nil)
  then
    request_handle:streamInfo():dynamicMetadata():set("envoy.lua", "requestBody", "-")
  else
    local request_body_data = request_body_buffer:getBytes(0, request_body_buffer:length())
    request_handle:streamInfo():dynamicMetadata():set("envoy.lua", "requestBody", request_body_data)
  end
end

function envoy_on_response(response_handle)
  local response_body_buffer = response_handle:body()
  if(response_body_buffer == nil)
  then
    response_handle:streamInfo():dynamicMetadata():set("envoy.lua", "responseBody", "-")
  else
    local response_body_data = response_body_buffer:getBytes(0, response_body_buffer:length())
    response_handle:streamInfo():dynamicMetadata():set("envoy.lua", "responseBody", response_body_data)
  end
end

2、利用Envoy File access log实现对dynamicMetadata内容的打印

参考:https://www.envoyproxy.io/docs/envoy/latest/configuration/observability/access_log/usage#config-access-log-default-format

Envoy打印请求和响应Body

日志打印设置如下:

[%START_TIME%] "%REQ(:METHOD)% %REQ(X-ENVOY-ORIGINAL-PATH?:PATH)% %PROTOCOL%" %RESPONSE_CODE% %RESPONSE_FLAGS% %BYTES_RECEIVED% %BYTES_SENT% %DURATION% %DURATION% "%REQ(X-FORWARDED-FOR)%" "%REQ(USER-AGENT)%" "%REQ(X-REQUEST-ID)%" "%REQ(:AUTHORITY)%" "%UPSTREAM_HOST%" %DYNAMIC_METADATA(envoy.lua)%

 

相关标签: Envoy