使用 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"
运行此代码将产生这个可爱的输出:
我,[2009-09-02 10:49:39#27562] 信息——:信息 W,[2009-09-02 10:49:39#27562] 警告——:警告 E,[2009-09-02 10:49:39#27562] 错误——:错误 F,[2009-09-02 10:49:39#27562] 致命——:致命
但是,如果我取消注释 require 'activerecord' 行,我会得到这个:
信息 警告 错误 致命的
因此,我在查看 activesupport 之后进行了一些搜索:
我找到了以下“工作解决方案”
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
使用上述内容,我得到了我喜欢的输出。然而,在我看来,这看起来很恶心,不像Ruby。有谁知道是否有更简单的方法来获得所需的结果?
谢谢!