How to log something in Rails in an independent log file?

akshat picture akshat · Dec 3, 2008 · Viewed 75.8k times · Source

In rails I want to log some information in a different log file and not the standard development.log or production.log. I want to do this logging from a model class.

Answer

Thiago Arrais picture Thiago Arrais · Dec 3, 2008

You can create a Logger object yourself from inside any model. Just pass the file name to the constructor and use the object like the usual Rails logger:

class User < ActiveRecord::Base
  def my_logger
    @@my_logger ||= Logger.new("#{Rails.root}/log/my.log")
  end

  def before_save
    my_logger.info("Creating user with name #{self.name}")
  end
end

Here I used a class attribute to memoize the logger. This way it won't be created for every single User object that gets created, but you aren't required to do that. Remember also that you can inject the my_logger method directly into the ActiveRecord::Base class (or into some superclass of your own if you don't like to monkey patch too much) to share the code between your app's models.