Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add current time before log message

I created a custom logger for my application, called CRON_LOG, just by adding this piece of code to config/environment.rb

CRON_LOG = Logger.new("#{Rails.root}/log/cron.log")
CRON_LOG.level = Logger::INFO

And then, when I want to log something, just do that:

CRON_LOG.info "something"

It works fine, but I'd like to add the current timestamp before each log message. Of course I can just add Time.now to my log message, but I'd like to know if there is a way to add it as default to every log message. How can I do that ?

Thanks.

like image 882
Brian Avatar asked Mar 02 '11 20:03

Brian


2 Answers

The easiest way to make a SysLog-formatted logger is to assign a formatter directly:

logger = Logger.new Rails.root.join('path', 'to', 'log')
logger.formatter = Logger::Formatter.new
logger.info 'Hello, world!'
# Writes:
#
#   I, [2011-06-02T20:02:34.579501 #15444]  INFO -- : Hello, world!
like image 50
stephencelis Avatar answered Oct 20 '22 02:10

stephencelis


You can redefine the proper method (e.g. adding the following to environment.rb or in an initializer):

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

[Caution: this could disrupt other loggers; see Stephen's answer for a safe solution - jph]

like image 26
Alberto Santini Avatar answered Oct 20 '22 03:10

Alberto Santini