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

查看:21
本文介绍了如何在独立日志文件中记录 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

这里我使用了一个类属性来记忆记录器.这样就不会为每个创建的 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天全站免登陆