gpt4 book ai didi

ruby-on-rails - 如何让 Rails 记录我的 Rack::CommonLogger 消息?

转载 作者:太空宇宙 更新时间:2023-11-03 17:58:50 24 4
gpt4 key购买 nike

我正在使用 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 一起使用,则不会捕获缓存消息。

关于ruby-on-rails - 如何让 Rails 记录我的 Rack::CommonLogger 消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8610707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com