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)
If you enjoyed this post, make sure you subscribe to my RSS feed!










2 Comments
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_ENVandRAILS_ROOThas been replaced byRails.envandRails.rootrespectively.Thanks tony.
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”)