开发者

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.


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!


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]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜