Rails:在lib目录中记录代码吗? [英] Rails: Logging for code in the lib directory?

查看:53
本文介绍了Rails:在lib目录中记录代码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为lib目录中保存的代码配置日志记录的最佳/最简便方法是什么?

What is the best/easiest way to configure logging for code kept in the lib directory?

推荐答案

有两种解决方法:

  • 假定您的库是自包含的并且有一个模块,则可以向模块添加logger属性,并在库代码中的任何地方使用该属性.

  • Assuming your library is self-contained and has a module, you can add a logger attribute to your module and use that everywhere in your library code.

module MyLibrary
  mattr_accessor :logger
end

然后您可以在config/initializers/中使用初始化程序,或者在config/environment.rb中使用config.after_initialize块来初始化记录器,如下所示:

You then either use an initializer in config/initializers/, or an config.after_initialize block in config/environment.rb to initialize your logger, like so:

require 'mylibrary'
MyLibrary.logger = Rails.logger

这仍然允许您使用Rails外部脚本中的自包含库.有时候很好.

This would still allow you to use your self-contained library from scripts outside of Rails. Which is nice, on occasion.

如果在没有Rails的情况下使用图书馆真的没有任何意义,那么您也可以直接使用Rails.logger.

If using your library without Rails really doesn't make sense at all, then you can also just use Rails.logger directly.

无论哪种情况,您都在使用标准的Ruby Logger.另外请记住,从理论上讲,记录器可能是nil.

In either case, you're dealing with a standard Ruby Logger. Also keep in mind that, in theory, the logger may be nil.

这篇关于Rails:在lib目录中记录代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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