I want to use this request = Rack::Request.new(env)
to log the headers present in request.env
, but the issue here is it will not only consist of the additional headers
we are passing, but it also consists of default headers, how to ignore it and only print the additional headers
?
To read and log HTTP header in Ruby on Rails, there is no middleware or gem required. Because access to the headers and a logger is already included to Rails.
I would add a small before_action
to the application_controller.rb
to add a specific header I am interested in like this:
# in app/controllers/application_controller.rb
before_filer :log_headers
private
def log_headers
Rails.looger.info "My API key: #{request.headers['MY-API-KEY']}"
end
Or you can log all headers, except some, like this:
def log_headers
headers_to_exclude = ['FOO', 'BAR']
headers_of_interest = request.headers.env.except(*headers_to_exclude)
Rails.looger.info "headers: #{headers_of_interest}"
end
Or you can only log headers explicitly named, like this:
def log_headers
headers_to_include = ['FOO', 'BAR']
headers_of_interest = request.headers.env.slice(*headers_to_include)
Rails.looger.info "headers: #{headers_of_interest}"
end
The list of headers to include or exclude could be extracted into a constant and the logic could be placed into a concern.