简体   繁体   English

Ruby Monkey Patched Logger在Rails控制台中不起作用

[英]Ruby Monkey Patched Logger does not work in Rails Console

I have some helper methods on my ActiveSupport::BufferedLogger such as displaying KeyValue pairs, it all works fine from rails s but fails in rails c 我有我的ActiveSupport :: BufferedLogger一些辅助方法,如显示的键值对,这一切工作正常,从轨秒 ,但在轨C未能

In rails s, I can see that my Logger extends BufferedLogger and that is the class I have chosen to MonkeyPatch, I have also tested this out with ActiveSupport::Logger as well. 在rails中,我可以看到我的Logger扩展了BufferedLogger,这是我选择用于MonkeyPatch的类,我也使用ActiveSupport :: Logger对此进行了测试。

I had thought that rails c ran through the same initializers that rails s used, am I wrong in thinking that? 我以为Rails c会通过与Rails所使用的初始化程序相同的方式运行,我是否认为这是错误的?

Do I need to run some sort of initializer when starting rails c? 启动rails c时是否需要运行某种初始化程序?

Location of my file is: 我的文件位置是:

  • config/initializers/active_support_logger.rb config / initializers / active_support_logger.rb

Error is here: 错误在这里:

在此处输入图片说明

Sample Snippet listed here 此处列出了示例代码段

class ActiveSupport::BufferedLogger

    def kv(key, value)
        info('%-50s %s' % ["#{key}: ".brown, value])
    end

    def line
        info(@@l.brown)
    end

    def block(message)
        line
        info(message)
        line
    end

end

I recommend subclassing ActiveSupport::Logger (or ActiveSupport::BufferedLogger if you really want though it's deprecated in Rails 4) instead of monkey-patching. 我建议将ActiveSupport::Logger (或者如果确实希望,尽管在Rails 4中不推荐使用ActiveSupport::BufferedLogger子类ActiveSupport::Logger而不是猴子补丁。 Rails provides a configuration option to override the logger instance used by the app. Rails提供了一个配置选项来覆盖应用程序使用的记录器实例。 This works in any context that loads the Rails environment, including the server and console. 这可以在加载Rails环境的任何上下文中使用,包括服务器和控制台。

There are a number of ways you can do this; 您可以通过多种方法来执行此操作。 a quick and dirty way to get you started is to just define the class and set the logger instance in an initializer that will get loaded during the initialization process of the Rails environment: 一种快速而肮脏的入门方法是只定义类并在初始化器中设置记录器实例,该初始化器将在Rails环境的初始化过程中加载:

# config/initializers/my_logger.rb

class MyLogger < ::ActiveSupport::Logger 
  # additional methods and overrides
end

Rails.logger = MyLogger.new(Rails.root.join("log", "#{Rails.env}.log"))

For more info, check out the Rails guide to debugging applications: http://guides.rubyonrails.org/debugging_rails_applications.html#the-logger 有关更多信息,请查看有关调试应用程序的Rails指南: http : //guides.rubyonrails.org/debugging_rails_applications.html#the-logger

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM