繁体   English   中英

如何获得Rails记录我的Rack :: CommonLogger消息?

[英]How do I get Rails to log my Rack::CommonLogger messages?

我正在使用ruby gem rest-clientrest-client-components

Rest-client-components使用Rack :: CommonLogger启用请求日志记录。

启用它的说明使用STDOUT:

require 'restclient/components'
RestClient.enable Rack::CommonLogger, STDOUT

这在开发中工作正常,但是当我使用Apache / Passenger(mod_rails)进行生产时,在production.log中看不到来自rest-client的任何消息。 有没有一种方法可以将Rack :: CommonLogger与Rails日志集成在一起? 还是至少将其写入文件? 前者更有用,因为它很容易看到上下文,但后者总比没有好。

谢谢。

这是我想出的解决方案。 感谢@crohr为我指出正确的方向。

首先,创建一个新的Logger类。 Rails默认为ActiveSupport :: BufferedLogger,因此我们将对其进行扩展。

# lib/rest_client_logger.rb
class RestClientLogger < ActiveSupport::BufferedLogger
  def write(msg)
    add(INFO, msg)
  end
end

然后告诉Rails使用新的记录器。

# application.rb
log_file = File.open("log/#{Rails.env}.log", 'a')
log_file.sync = true  # turn on auto-flushing at the file level so we get complete messages
config.logger = RestClientLogger.new(log_file)
config.logger.auto_flushing = !Rails.env.production?  # turn off auto-flushing at the logger level in production for better performance

最后,告诉rest-client使用您的新记录器。

# config/initializers/rest_client.rb
RestClient.enable Rack::CommonLogger, Rails.logger

局限性:

如果您将Rack :: Cache与rest-client-components一起使用,则不会捕获缓存消息。

暂无
暂无

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

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