ActiveRecord干扰Logger

时间:2009-09-03 03:24:46

标签: ruby activerecord logging activesupport

似乎使用ActiveRecord(需要ActiveSupport)与Logger类混淆,导致困难。这可以通过一些示例代码看出:

require 'rubygems'
#require 'activerecord'
require 'logger'

log = Logger.new(STDERR)
log.sev_threshold = Logger::INFO
log.datetime_format = "%Y-%m-%d %H:%M:%S"

log.debug "debug"
log.info "info"
log.warn "warn"
log.error "error"
log.fatal "fatal"

运行此代码将产生这个可爱的输出:

I, [2009-09-02 10:49:39#27562]  INFO -- : info
W, [2009-09-02 10:49:39#27562]  WARN -- : warn
E, [2009-09-02 10:49:39#27562] ERROR -- : error
F, [2009-09-02 10:49:39#27562] FATAL -- : fatal

但是,如果我取消注释require'activerecord'行,我会改为:

info
warn
error
fatal 

所以我在查看activesupport后进行了一些搜索:

logger.rb

我找到了以下“工作解决方案”

log = Logger.new(STDERR)
log.sev_threshold = Logger::INFO
log.datetime_format = "%Y-%m-%d %H:%M:%S"
class Formatter
      Format = "%s, [%s#%d] %5s -- %s: %s\n"

      attr_accessor :datetime_format

      def initialize
        @datetime_format = nil
      end

      def call(severity, time, progname, msg)
        Format % [severity[0..0], format_datetime(time), $$, severity, progname, msg2str(msg)]
      end

      private
        def format_datetime(time)
          if @datetime_format.nil?
             time.strftime("%Y-%m-%dT%H:%M:%S.") << "%06d " % time.usec
          else
            time.strftime(@datetime_format)
          end
        end

        def msg2str(msg)
          case msg
          when ::String
            msg
          when ::Exception
            "#{ msg.message } (#{ msg.class })\n" <<
            (msg.backtrace || []).join("\n")
          else
            msg.inspect
          end
        end
end
f=Formatter.new
f.datetime_format = "%Y-%m-%d %H:%M:%S"
log.formatter=f 

使用上面的内容,我得到了我喜欢的输出。然而,这对我来说似乎是粗暴的,而且是非鲁莽的。有谁知道是否有更简单的方法来获得理想的结果?

谢谢!

1 个答案:

答案 0 :(得分:6)

同样的问题在最后一小时给我带来了麻烦,但解决方案非常简单。

ActiveSupport使用SimpleFormatter,您必须手动设置“旧”Formatter。

require 'rubygems'
require 'active_support'
require 'logger'

log = Logger.new(STDERR)
log.sev_threshold = Logger::INFO
log.datetime_format = "%Y-%m-%d %H:%M:%S"
log.formatter = Logger::Formatter.new

Ps:Sry因为我的英语不好:)