Rails4中的自定义记录器

Rails4中的自定义记录器

本文介绍了Rails4中的自定义记录器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

看起来像Rails4的记录器,与Rails3的记录器不同,它最终支持自定义格式化程序,就像ruby stdlib记录器一样.

It looks like Rails4's logger, unlike Rails3's, finally supports a custom formatter, like the ruby stdlib logger again.

Rails.logger.formatter  # => #<ActiveSupport::Logger::SimpleFormatter:0x007ff81757d890 @datetime_format=nil>
Rails.logger.formatter = SomeFormatterClass

但是,当我尝试为它提供一个足以满足stdlib Logger格式化程序的格式化程序类时:

However, when I try to give it a formatter class that would be sufficient for stdlib Logger formatter:

[2014-03-12 16:23:27] ERROR NoMethodError: undefined method `tagged' for #<FormattedRailsLoggerFormatter:0x007fd816545ad8>
/Users/jrochkind/.gem/ruby/1.9.3/gems/activesupport-4.0.3/lib/active_support/tagged_logging.rb:67:in `tagged'
/Users/jrochkind/.gem/ruby/1.9.3/gems/railties-4.0.3/lib/rails/rack/logger.rb:20:in `call'

有人知道,自定义格式化程序实际上是Rails4的受支持功能吗?以及如何在任何地方记录下来?

Does anyone know, is a custom formatter actually a supported feature of Rails4? And is how you are meant to do it documented anywhere?

推荐答案

回答我自己的问题,我已经知道了.

Answering my own question, I've figured it out.

Rails4提供了一个配置变量config.log_formatter.您可能会在config/application.rb中将其与其他应用程序配置一起设置.

Rails4 provides a config variable, config.log_formatter. You would probably set it in your config/application.rb, along with other application config.

您应该将其设置为实现stdlib Logger Formatter接口的对象:基本上,您必须提供方法call(severity, time, progname, msg),该方法返回格式化的日志行.

You should set it to an object implementing the stdlib Logger Formatter interface: Basically, you have to provide a method call(severity, time, progname, msg) that returns the formatted log line.

请注意,将其设置为对象,而不是类名,例如:

Note you set it to an object, NOT the class name, eg:

config.log_formatter = MyFormatter.new

您不应该不要尝试直接设置Rails.logger.formatter-Rails希望您通过config进行设置,并且做一些棘手的事情来使您的formatter和logger在您使用Rails时正常工作使用配置.您可以在在此处跟踪源代码. (感谢github,它非常棒的代码搜索和显示ui,这是我如何跟踪并找出config.log_formatter的存在的原因)

You should not try to set Rails.logger.formatter directly -- Rails expects you to set it via config, and does some tricky stuff to make your formatter and logger work properly with Rails when you use the config. You can see that, as well as see that indeed config.log_formatter is used, in Rails source code here. (Thanks to github and it's awesome code search and display ui, is how I tracked this down and figured out the existence of config.log_formatter)

在Rails4中,您应该不需要仅使用自定义日志格式化程序就需要猴子Rails的任何部分,而只需使用config.log_formatter. (在Rails3中,您确实需要猴子补丁一个或另一个以获得自定义日志格式).

In Rails4, you should not need to monkey-patch any parts of Rails just to use a custom log formatter, just use config.log_formatter instead. (In Rails3 you did need to monkey-patch one or another to get custom log formatting).

这篇关于Rails4中的自定义记录器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 23:33