You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails 7.1.2如何配置日志同时输出至STDOUT与log/production.log

Rails 7.1 实现日志同时输出到STDOUT和文件

在Rails 7.1中,ActiveSupport::Logger.broadcast方法已被移除,官方推荐使用ActiveSupport::BroadcastLogger类来实现多目标日志输出。你可以按以下方式修改config/environments/production.rb中的配置:

# 创建STDOUT日志实例并配置格式与标签
stdout_logger = ActiveSupport::Logger.new(STDOUT)
  .tap { |logger| logger.formatter = ::Logger::Formatter.new }
  .then { |logger| ActiveSupport::TaggedLogging.new(logger) }

# 创建文件日志实例,指定路径、滚动策略并配置格式
file_logger = ActiveSupport::Logger.new(Rails.root.join('log', 'production.log'), 3)
  .tap { |logger| logger.formatter = ::Logger::Formatter.new }
  .then { |logger| ActiveSupport::TaggedLogging.new(logger) }

# 组合两个日志实例,实现同时输出
config.logger = ActiveSupport::BroadcastLogger.new(stdout_logger, file_logger)

关键细节说明:

  • ActiveSupport::BroadcastLogger会将日志消息转发给传入的所有日志实例,确保STDOUT和文件同时收到日志
  • Rails.root.join('log', 'production.log')使用Rails根目录构建文件路径,避免硬编码路径带来的适配问题
  • 第二个参数3表示文件日志的滚动策略,会保留最近3个旧日志文件(超出后自动清理)
  • 两个日志实例都单独配置了格式化器和标签日志,保证输出格式一致

如果需要复用Rails默认的日志格式,可将logger.formatter = ::Logger::Formatter.new替换为logger.formatter = config.log_formatter。

内容的提问来源于stack exchange,提问作者Manuel Meurer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 13:05:12