Include params/request information in Rails logger?

13,208

Solution 1

(Responding a long time after this was asked, but maybe it will help the next person.)

I just did something similar.

1) you need to override your logger separately from logging request-leve details. Looks like you've figured customizing your logger out. Answer is here: Rails logger format string configuration

2) I log the request and response of all requests into my service. Note, that Rails puts a tonne of stuff into the headers, so just straight dumping the request or the headers is probably a bad idea. Also of note, my application is primarily accessed via an API. If yours is primarily a web-app, as I'm guessing most people's are, you probably don't want to inspect the response.body as it will contain your html.

class ApplicationController < ActionController::Base 
  around_filter :global_request_logging
...
  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 
end

Solution 2

This should work! :) cheers.

logger.info({:user_agent => request.user_agent, :remote_ip => request.remote_ip}.inspect)

logger.info(params.inspect)

By the by.. This should be placed in your controllers action. Ex: If you place it in your create action it should also log the user_agent i.e the browser, remote_ip i.e the remote ip of the user and all the params.

Share:
13,208
Admin
Author by

Admin

Updated on June 28, 2022

Comments

  • Admin
    Admin almost 2 years

    I'm trying to get some more information into my Rails logs, specifically the requested URI or current params, if available (and I appreciate that they won't always be). However I just don't seem able to. Here's what I've done so far:

    #config/environments/production.rb
    config.logger = Logger.new(config.log_path)
    config.log_level = :error
    config.logger.level = Logger::ERROR
    
    #config/environment.rb
    class Logger
      def format_message(level, time, progname, msg)
        "**********************************************************************\n#{level} #{time.to_s(:db)} -- #{msg}\n"
      end  
    end
    

    So I can customize the message fine, yet I don't seem to be able to access the params/request variables here. Does anyone know if this is possible, and if so how? Or if there's a better way to get this information? (Perhaps even something Redis based?)

    Thanks loads,

    Dan