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.




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.
sure does! thanx.
That helped me. Thank you!
yay! it worked for me!
Thanks for posting this, Jason. Helped a bunch!
Just came across this tip from a rails logger from model….was trying to debug info in the cancan Ability model.
Thanks
That helped me understand my problem, thank you!
It helped me! Thanks!
help me too! thanks!
Thanks a ton! That’s super helpful. It seems like the logger is something that should just be inherited by everything, but appending “Rails.” is no big deal I suppose.
Thank you, Jason!
This was driving me nuts. It seemed like such a simple thing, too. Little did I know that it WAS a simple thing once I found your blog. ;-)
Again, thanks and cheers!
Thank you
It helped me. Just what I was looking for at a WTF moment.
Thank you so much for posting it. I don’t know how long it would have taken me to find it otherwise.
Thanks for being a great member of the Rails community. It’s people like you that make it thrive. (Why is it that when I’m really thanking someone it starts sounding ironic? Well, it’s not.)