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.
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.