annoying Logger/ActiveRecord problem

0 views
Skip to first unread message

Mister Rohit

unread,
Sep 2, 2009, 10:52:42 AM9/2/09
to hartford-r...@googlegroups.com
Hey guys, just throwing it out to the list to see if anyone is
familiar with this. I have some code that uses 'logger', but when I
include 'activerecord', it seems to change the behavior of the logger
class. Googling brings me a little deeper than I want to go, but here
is a quick demonstration of the problem. Test code follows:

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"

Running this code will produce this lovely output:
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

However, if I uncomment the require 'activerecord' line, I instead get this:

info
warn
error
fatal

Does anyone know any way to reference the old Logger class while still
using ActiveRecord?

rohitunderhill

unread,
Sep 2, 2009, 11:33:59 AM9/2/09
to Hartford Ruby Brigade
Ok I have a working solution. If anyone is curious, after looking at
this: http://github.com/rails/rails/blob/669fd84910586d4c791b6f5bf4320f68ac7845aa/activesupport/lib/active_support/core_ext/logger.rb

I tried the following and everything is working perfectly. I'm sure
there is a better way to do what I want. It does not appear that
there is a well-documented path though.... The following certainly is
kindof awful.

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
Reply all
Reply to author
Forward
0 new messages