Using the Rails logger outside of models and controllers

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.

Post to Twitter Post to Delicious Delicious Post to Digg Digg This Post Post to Facebook Facebook Post to Reddit Reddit This Post

No related posts.

Tags:

11 Responses to “Using the Rails logger outside of models and controllers”

  1. Jason Hawkins 10. Aug, 2009 at 3:26 pm #

    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 :(

  2. karunakar 13. Aug, 2009 at 12:24 pm #

    Nice tip… Thx….

    Will it work in the rake tasks? I hope it should…..

  3. raghunadh 13. Aug, 2009 at 12:37 pm #

    Good one!!

  4. cndevelopment 19. Aug, 2009 at 6:59 am #

    Thanks for that Jason, it surely did.

  5. cndevelopment 19. Aug, 2009 at 10:59 am #

    Thanks for that Jason, it surely did.

  6. Adam Grant 11. Sep, 2009 at 12:08 am #

    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.

  7. Ki 15. Oct, 2009 at 11:04 am #

    Thanks, Jason, it really works.

  8. eno 18. Nov, 2009 at 10:41 am #

    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

  9. jotermoter 01. Jul, 2010 at 4:47 pm #

    It helped me.

    Tx

  10. zuko_uno 27. Jul, 2010 at 4:20 am #

    Thx for help!

  11. Neil Hankey 23. Aug, 2010 at 6:43 am #

    Fine! Thank you.

Leave a Reply