提问人:Manuel Meurer 提问时间:11/15/2023 最后编辑:Manuel Meurer 更新时间:11/17/2023 访问量:158
Rails 7.1,日志到 STDOUT 和 log/production.log
Rails 7.1, log to STDOUT and log/production.log
问:
在新的 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) }
这会告诉 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)
但似乎这些说明适用于 Rails < 7.1,因为我收到错误广播“for ActiveSupport::Logger:Class”。NoMethodError: undefined method
如何在 Rails 7.1 中做到这一点?
答:
3赞
Alex
11/15/2023
#1
Rails 添加了新的类来处理广播:v7.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
https://api.rubyonrails.org/classes/ActiveSupport/BroadcastLogger.html
由于您可以传递给 ,这使得设置更加简洁: https://github.com/rails/rails/commit/3b012a52540f7e4564d70f1955785bde32269a3d:rails v7.1
formatter
new
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))
)
评论
0赞
Manuel Meurer
11/17/2023
太好了,谢谢你的解释和链接,亚历克斯!这是我最终得到的精简版本: # config/environments/production.rb config.logger = [STDOUT, “log/production.log”].map do |destination|ActiveSupport::Logger.new(destination) .tap { _1.formatter = ::Logger::Formatter.new } .then { ActiveSupport::TaggedLogging.new _1 } end.then { ActiveSupport::BroadcastLogger.new(*_1) } (pff,注释中没有 Markdown 或换行符??
1赞
Alex
11/17/2023
@ManuelMeurer在评论中使用,没有换行符,一些 Markdown 有效。在末尾看到一点更新^。single backticks
1赞
Manuel Meurer
11/17/2023
在 Rails 7.1.1 中,多个记录器似乎存在问题: github.com/rails/rails/issues/49745 如果出现“没有将字符串隐式转换为整数”,请等待 Rails 7.1.2
评论