【问题标题】:How do I get Rails to log my Rack::CommonLogger messages?如何让 Rails 记录我的 Rack::CommonLogger 消息?
【发布时间】:2011-12-22 23:03:06
【问题描述】:

我正在使用 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 日志集成?或者至少将其写入文件?前者更有用,因为它很容易看到上下文,但后者总比没有好。

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby passenger rack rest-client


    【解决方案1】:

    这是我想出的解决方案。 感谢@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 一起使用,则不会捕获缓存消息。

    【讨论】:

      猜你喜欢
      • 2011-01-15
      • 2021-04-27
      • 1970-01-01
      • 2012-05-24
      • 1970-01-01
      • 2012-06-15
      • 2018-04-29
      • 2014-04-08
      • 1970-01-01
      相关资源
      最近更新 更多