标准的
Ruby记录器(即
::Logger
)可以在每次写入后自动刷新吗?
更新:我正在设置一个自定义日志格式化程序,按照How to get timestamps in your ruby on rails logs:
class Foo def initialize(params = {}) @logger = Logger.new $stdout @logger.formatter = LogFormatter.new @logger.level = params.include?(:log) ? params[:log] : Logger::INFO # ... end class LogFormatter < Logger::Formatter def call(severity,time,progname,message) timestamp = time.iso8601 log_msg = "#{timestamp}#{" [#{severity}]" if %w{ERROR WARN}.include? severity} " if message.is_a? Exception log_msg += "#{message.message}" log_msg += ": #{message.backtrace.join "\n#{timestamp} "}" unless message.backtrace.blank? else log_msg += message end "#{log_msg}\n" end end end
我试图使用idlefingers的建议如下:
def initialize(params = {}) Rails.logger.auto_flushing = 1 @logger = Logger.new $stdout @logger.formatter = LogFormatter.new @logger.level = params.include?(:log) ? params[:log] : Logger::INFO end
但没有骰子. @ logger.auto_flushing = 1也不为我工作.我究竟做错了什么?
更新:事实证明,ActiveSupport的::Logger
只是包装标准的Ruby :: Logger.所以我的问题毕竟是关于Ruby而不是Rails的.
解决方法
原来,这只是打开底层IO对象的sync属性的问题:
def initialize(params = {}) $stdout.sync = true unless RAILS_ENV == 'production' @logger = Logger.new $stdout @logger.formatter = LogFormatter.new @logger.level = params.include?(:log) ? params[:log] : Logger::INFO end