You can use the Rails logger outside of Rails models in at least version 2.3.X and up of Rails. You might be used to doing the following in your models or controllers:
logger.info "Some debugging info I want to see in my development log."
If you make a regular model that doesn’t inherit from ActiveRecord, though, you may see the following error:
undefined local variable or method `logger' for #<Class:0x42fd77c>
The solution is to call Rails.logger.info (or debug, or warn) as follows:
Rails.logger.info "Some debugging info I want to see in my development log."
I hope that helps someone.
Delicious
Digg This Post
Facebook
Reddit This Post
No related posts.





It helped me*. I'd even do a commercial where I give one of those (paid) testimonials about it. “Jason Seifer's Rails logger did the trick for me!” Something like that. We'd sell millions.
*I don't know what any of this means :(
Nice tip… Thx….
Will it work in the rake tasks? I hope it should…..
Good one!!
Thanks for that Jason, it surely did.
Thanks for that Jason, it surely did.
You can also use the constant RAILS_DEFAULT_LOGGER to get the same thing.
In gems/rails-2.3.2/lib/initializer.rb:
=====================
module Rails
def logger
if defined?(RAILS_DEFAULT_LOGGER)
RAILS_DEFAULT_LOGGER
else
nil
end
end
end
=================
That way you can easily set the constant (ex: in testing) without having to stub and mock Rails and #logger (in case you don't have access to them for some reason…).
But in any case, very good tip! I always used the constant, glad to know there's another way.
Thanks, Jason, it really works.
I think a better solution would be to
module WithRailsLogger
def logger; Rails.logger; end
end
and then include that module into the modules/classes you are working with or even directly into Object
Object.send :include, WithRailsLogger
It helped me.
Tx
Thx for help!
Fine! Thank you.