如何在Rails的独立日志文件中记录某些内容? [英] How to log something in Rails in an independent log file?

查看:180
本文介绍了如何在Rails的独立日志文件中记录某些内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在rails中,我想将一些信息记录在不同的日志文件中,而不是标准的development.log或production.log中.我想从模型类中进行日志记录.

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.

推荐答案

您可以从任何模型内部自己创建Logger对象.只需将文件名传递给构造函数,然后像通常的Rails logger:

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

在这里,我使用了class属性来记录记录器.这样,就不会为创建的每个User对象都创建它,但是您不需要这样做.还要记住,您可以将my_logger方法直接注入到ActiveRecord::Base类中(或者,如果您不想过多地修补补丁,则可以注入到自己的某些超类中),以在应用程序的模型之间共享代码.

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.

这篇关于如何在Rails的独立日志文件中记录某些内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆