【问题标题】:How do I make rails' logger use ANSI sequences when outputting to screen, but not when logging to a file?如何使 rails 的记录器在输出到屏幕时使用 ANSI 序列,但在记录到文件时不使用?
【发布时间】:2026-01-26 19:30:01
【问题描述】:

我对不得不在生产服务器 (log/production.log) 上的日志中切断 ANSI 序列感到恼火,因此我将 config.colorize_logging = false 添加到 config/environments/production.rb。但是现在当我运行控制台 (bin/rails c) 时,输出也没有着色。为什么会这样?有没有办法让记录器在输出到屏幕时使用 ANSI 序列,而在记录到文件时不使用它们?

UPD 我能弄清楚的。当rails app 启动时,creates logger 会登录到一个文件:

Rails.logger ||= config.logger || begin
  path = config.paths["log"].first
  unless File.exist? File.dirname path
    FileUtils.mkdir_p File.dirname path
  end

  f = File.open path, 'a'
  f.binmode
  f.sync = config.autoflush_log # if true make sure every write flushes

  logger = ActiveSupport::Logger.new f
  logger.formatter = config.log_formatter
  logger = ActiveSupport::TaggedLogging.new(logger)
  logger
rescue StandardError
  logger = ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDERR))
  logger.level = ActiveSupport::Logger::WARN
  logger.warn(
    "Rails Error: Unable to access log file. Please ensure that #{path} exists and is writable " +
    "(ie, make it writable for user and group: chmod 0664 #{path}). " +
    "The log level has been raised to WARN and the output directed to STDERR until the problem is fixed."
  )
  logger
end

然后attaches to it another logger 将消息输出到STDOUT

def log_to_stdout
  wrapped_app # touch the app so the logger is set up

  console = ActiveSupport::Logger.new($stdout)
  console.formatter = Rails.logger.formatter
  console.level = Rails.logger.level

  Rails.logger.extend(ActiveSupport::Logger.broadcast(console))
end

由于某种原因,当我运行 ./bin/rails c 时,在 ActiveSupport::Logger#initialize 处打破 byebug 关键字永远不会成功。

UPD好吧,罪魁祸首是springconsole(或者我应该说activerecord)创建了它的记录器here

console do |app|
  require "active_record/railties/console_sandbox" if app.sandbox?
  require "active_record/base"
  console = ActiveSupport::Logger.new(STDERR)
  Rails.logger.extend ActiveSupport::Logger.broadcast console
end

【问题讨论】:

    标签: ruby-on-rails ruby logging ansi-colors


    【解决方案1】:

    在控制台中打开 colorized_logging 的一种方法是将其显式设置为 true,如下所示:

    $ bin/rails c
    :001 > Rails.application.config.colorize_logging
     => false 
    :002 > Rails.application.config.colorize_logging = true 
     => true
    :003 > Rails.application.config.colorize_logging
     => true 
    

    可能有一种方法可以在每次加载控制台时通过使用.irbrc 文件自定义控制台来自动设置此设置

    【讨论】:

    • 此设置无法解决任何问题。如果我在控制台中启用它,则会使用 ANSI 序列记录 sql 查询。关键是在输出到屏幕时使logger 为输出着色,而不是在记录到文件时。相同的输出同时进入屏幕和文件。