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 中做到这一点?
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
由于rails v7.1您可以传递formatter给new,这使得设置更加清晰: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)
| 归档时间: |
|
| 查看次数: |
1272 次 |
| 最近记录: |