Logging your Rails model (the easy way)

In one of my Rails applications, I have some pretty heavy tasks in my models. I decided to log to different files for two of my models so that I can easily make sure these tasks are performed correctly without going through my application log. I also call some of my model methods with rake tasks so it’s nice to have that action logged. The code below implements a custom log for the SomeClass model.

class SomeClass < ActiveRecord::Base
     LOGFILE = File.join(RAILS_ROOT, '/log/', "someclass_#{RAILS_ENV}.log")
 
     def self.do_something
          log "I am doing something"
     end
 
     def do_something_else
          SomeClass.log "Tried to do something else, but screwed up.", :error
     end
 
     def self.log(message, severity = :info)  
         @model_log ||= ActiveSupport::BufferedLogger.new(LOGFILE)
         @model_log.send severity, "[#{Time.now.to_s(:db)}] [#{severity.to_s.capitalize}] #{message}\n" 
     end
end

This will create separate logs for all of your environments. Notice that I reference the class when I log from an instance method. This is working great for me. Anyone have a better way?

No TweetBacks yet. (Be the first to Tweet this post)
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • MySpace
  • Slashdot
  • StumbleUpon
  • Technorati
  • TwitThis

If you enjoyed this post, make sure you subscribe to my RSS feed!

This entry was posted in Software and tagged , , , , . Bookmark the permalink. Both comments and trackbacks are currently closed.

2 Comments

  1. kaushik
    Posted April 18, 2012 at 9:00 pm | Permalink

    Hi, i know its been 3 years now, but still works great on Rails 3.2

    Secondly, if someone comes knocking, let me suggest that RAILS_ENV and RAILS_ROOT has been replaced by Rails.env and Rails.root respectively.

    Thanks tony.

  2. Posted June 11, 2012 at 2:08 am | Permalink

    Works here too.

    “/log/” pretty well denies benefit of File.join, better to do something like this:

    config.assets.logger = Logger.new File.join(Rails.root, “log”, “assets_#{Rails.env}.log”)