我正在使用 ruby gem rest-client与 rest-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 一起使用,则不会捕获缓存消息。
我是一名优秀的程序员,十分优秀!