【发布时间】: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好吧,罪魁祸首是spring,console(或者我应该说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