且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rails4中的自定义记录器?

更新时间:2023-02-16 17:49:12

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

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时正常工作使用配置.您可以在

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).