如何记录某个 url 的整个请求(headers、body 等)?

How to log an entire request (headers, body, etc) for a certain url?

我需要将包括 HTTP headers、正文等在内的所有请求记录到某个 url。我试过这段代码:

def index
  global_request_logging
end

private

def global_request_logging 
    http_request_header_keys = request.headers.keys.select{|header_name| header_name.match("^HTTP.*")}
    http_request_headers = request.headers.select{|header_name, header_value| http_request_header_keys.index(header_name)}
    logger.info "Received #{request.method.inspect} to #{request.url.inspect} from #{request.remote_ip.inspect}.  Processing with headers #{http_request_headers.inspect} and params #{params.inspect}"
    begin 
      yield 
    ensure 
      logger.info "Responding with #{response.status.inspect} => #{response.body.inspect}"
    end 
  end 

但是它说 request.headers 不包含名为 keys 的方法。我还认为应该有一种更简单的方法或标准来做到这一点。最好不要使用 gem.

它看起来像 request.headers returns 一个散列,但实际上,它 returns 一个没有 keysHttp::Headers 的实例方法已定义。

但是 Http::Headers 响应 env,其中 returns 原始环境哈希。因此以下作品:

http_request_header_keys = request.headers.env.keys.select do |header_name| 
  header_name.match("^HTTP.*")
end

或者您可以遍历所有键值对并将它们复制到另一个散列中:

http_envs = {}.tap do |envs|
  request.headers.each do |key, value|
    envs[key] = value if key.downcase.starts_with?('http')
  end
end

logger.info <<-LOG.squish
  Received     #{request.method.inspect} 
  to           #{request.url.inspect} 
  from         #{request.remote_ip.inspect}.  
  Processing 
  with headers #{http_envs.inspect} 
  and params   #{params.inspect}"
LOG

总结一下:

around_action :log_everything, only: :index

def index
  # ...
end

private
def log_everything
  log_headers
  yield
ensure
  log_response
end

def log_headers
  http_envs = {}.tap do |envs|
    request.headers.each do |key, value|
      envs[key] = value if key.downcase.starts_with?('http')
    end
  end

  logger.info "Received #{request.method.inspect} to #{request.url.inspect} from #{request.remote_ip.inspect}. Processing with headers #{http_envs.inspect} and params #{params.inspect}"
end

def log_response
  logger.info "Responding with #{response.status.inspect} => #{response.body.inspect}"
end

我正在使用它来获得完整的 headers:

request.headers.env.select do |k, _| 
  k.downcase.start_with?('http') ||
  k.in?(ActionDispatch::Http::Headers::CGI_VARIABLES)
end