如何记录某个网址的整个请求(标题,正文等)?

9 ruby logging ruby-on-rails ruby-on-rails-4

我需要将所有请求(包括HTTP标头,正文等)记录到某个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 
Run Code Online (Sandbox Code Playgroud)

但它表示request.headers不包含一个名为的方法keys.我还认为应该有一个更简单的方法或标准来做到这一点.优选地,不使用宝石.

spi*_*ann 14

它看起来像request.headers返回一个哈希,但事实上,它返回一个Http::Headers没有keys定义方法的实例.

但是Http::Headers响应env哪个返回原始的env哈希.因此这样的事情可能有效:

http_request_header_keys = request.headers.env.keys.select do |header_name| 
  header_name.match("^HTTP.*")
end
Run Code Online (Sandbox Code Playgroud)

或者您可以迭代所有键值对并将它们复制到另一个哈希:

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
Run Code Online (Sandbox Code Playgroud)

包装它:

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
Run Code Online (Sandbox Code Playgroud)


cap*_*013 7

我用它来获取完整的标题:

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