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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…