views:

201

answers:

2

Hi everyone,

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

A: 

you should look in the request class

like puts request.uri.

check here for more detail http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html

VP
Thanks VP, but it doesn't seem to work. I believe, because the Logger is configured before most of Rails is loaded, it doesn't have access to the @env variable, or indeed the params/request variables. @env is nil within the scope of the format_message, as is request, and request_uri thus errors too.
Dan Hill
A: 

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.

Shripad K
Hi Paddy, thanks for this. Whilst this would work, is there a way to automatically have the request/params available to the logger itself? I.e. if, rather than me calling logger.info/warn/error from the controller, it's been called from an exception being raised anywhere in the code. E.g. I may have in the code a wayward call to current_user.profesion.blank? This would error as profesion should be profession (undefined function on nil etc). It would be great in the log to have the url/current params as well as the stack trace.
Dan Hill
I tried that. But as you said Logger is configured before Rails is loaded. I found this article which i don't really know how helpful it might be: http://www.ubuntusolutions.org/2009/08/custom-logger-in-rails.html
Shripad K
Yea. The other way round it might be to somehow extend the class/code that calls the Raise/logger in the first place, to add some extra data into the msg? Even just the ActionController somewhere?
Dan Hill
This might help with the params problem. But is still too verbose.`ActionController::Base.logger = Logger.new(STDOUT)`
Shripad K