Rails 7.1,记录到 STDOUT 和 log/Production.log

Man*_*rer 5 logging ruby-on-rails ruby-on-rails-7

在新的 Rails 7.1.2 应用程序中,可以在以下位置找到以下行config/environments/production.rb

config.logger = ActiveSupport::Logger.new(STDOUT)
  .tap  { |logger| logger.formatter = ::Logger::Formatter.new }
  .then { |logger| ActiveSupport::TaggedLogging.new(logger) }
Run Code Online (Sandbox Code Playgroud)

这告诉 Rails 记录器记录到STDOUT.

我想配置它,以便它也记录到log/production.log,但我无法弄清楚我的一生......

在 Fly.io 的这篇文章中,它说添加这些行:

logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
volume_logger = ActiveSupport::Logger.new("/logs/production.log", 3)
logger = logger.extend ActiveSupport::Logger.broadcast(volume_logger)
Run Code Online (Sandbox Code Playgroud)

但这些说明似乎适用于 Rails < 7.1,因为我收到错误NoMethodError: undefined method 广播' for ActiveSupport::Logger:Class`。

我如何在 Rails 7.1 中做到这一点?

Ale*_*lex 6

Railsv7.1 添加了BroadcastLogger类来处理广播:

stdout_logger           = ActiveSupport::Logger.new(STDOUT)
stdout_logger.formatter = ::Logger::Formatter.new

file_logger             = ActiveSupport::Logger.new("log/production.log")
file_logger.formatter   = ::Logger::Formatter.new

tagged_stdout_logger    = ActiveSupport::TaggedLogging.new(stdout_logger)
tagged_file_logger      = ActiveSupport::TaggedLogging.new(file_logger)

broadcast_logger = ActiveSupport::BroadcastLogger.new(tagged_stdout_logger, tagged_file_logger)
config.logger    = broadcast_logger
Run Code Online (Sandbox Code Playgroud)

https://api.rubyonrails.org/classes/ActiveSupport/BroadcastLogger.html

https://guides.rubyonrails.org/upgrading_ruby_on_rails.html#rails-logger-now-returns-an-activesupport-broadcastlogger-instance


由于rails v7.1您可以传递formatternew,这使得设置更加清晰:https://github.com/rails/rails/commit/3b012a52540f7e4564d70f195578 ​​5bde32269a3d :

config.logger = ActiveSupport::BroadcastLogger.new(
  ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new($stdout,              formatter: Logger::Formatter.new)),
  ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new("log/production.log", formatter: Logger::Formatter.new))
)
Run Code Online (Sandbox Code Playgroud)

  • 在 Rails 7.1.1 中,多个记录器似乎存在问题:https://github.com/rails/rails/issues/49745 如果您得到“没有将字符串隐式转换为整数”,请等待 Rails 7.1.2 (2认同)