Using logger from rails cron jobs


#1

Hi. I’m trying to use logger from a rails cron job.

It works fine, but I’d like the standard ruby behavior of stamping each
log with date and time. How do I do this?

I’m trying:

Set up out logging

require ‘logger’
logger = Logger.new(STDERR)
logger.level = Logger::INFO
RAILS_DEFAULT_LOGGER = logger # Tell rails to log to our logger also

The logs show the messages fine, but no time stamps or severity level.

Thanks


#2

List R. wrote:

RAILS_DEFAULT_LOGGER = logger # Tell rails to log to our logger also

The logs show the messages fine, but no time stamps or severity level.

I submitted this over 2 months ago, so far nothing, perhaps I should
submit a patch…

http://dev.rubyonrails.org/ticket/2484

This is defined in activesupport’s clean_logger.rb file. This is because
Rails overrides the default logging format of Logger. You can override
this by overriding Logger#format_message

The code from clean_logger.rb is:
private
alias old_format_message format_message

 if method_defined?(:formatter=)
   def format_message(severity, timestamp, progname, msg)
     "#{msg}\n"
   end
 else
   def format_message(severity, timestamp, msg, progname)
     "#{msg}\n"
   end
 end

You can override format_message itself with a custom implementation or
you can override it to call old_format_message:

class Logger
def format_message *args
old_format_message *args
end
end

Hope this helps,

Zach


#3

List R. wrote:

RAILS_DEFAULT_LOGGER = logger # Tell rails to log to our logger also

Last post was slightly off in the last block I code I submitted, don’t
call old_format_message unless you have 1.8.3, but you can use the
following code to add your timestamp:

class Logger
def format_message(severity, timestamp, msg, progname)
“#{timestamp} #{msg}\n”
end
end

Zach