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. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">