No Pugs

they're evil

How to get timestamps in your ruby on rails logs

For some reason, BufferedLogger is the default logger in rubyonrails. This logger at this time has no way to customize it’s format, and what’s worse, is it’s format is practically unusable.

At some point most of us are going to encounter a situation where knowing when something was logged is nearly essential.

So, after fighting with rails for a while, here is how I got timestamps in my logs using rails 2.1.0

It’s worth pointing out that I made several errors while trying to do this, however the behavior of rails with a misconfigured logger was completely unhelpful in 90% of the situations I found myself in. So hopefully this can save somebody some time.

In environment.rb, inside the block:

  config.logger = + "/../log/#{RAILS_ENV}.log") 
  config.logger.formatter =

Then in development.rb, test.rb and production.rb:

config.logger.level = Logger::DEBUG

You can set this to whatever logging level is appropriate for the given environment. I personally use Logger::WARN for production and Logger::DEBUG for everything else.

Now, Logger::Formatter cannot be customized but at least it gives you a timestamp. This was good enough for me and if you’re satisfied then stop here.

If you need further customization, you can write your own formatter class. The interface is pretty straight forward, you simply needs to implement:

def call(severity, time, progname, msg) 
   #your code goes here that builds the entry you want to see in the logfile

Published on 07/10/2008 at 06:49PM under .

  • By Sid 11/25/2009 at 01:19AM

    Thanks Miles … just what I needed

  • By Ferdinand Svehla 01/09/2011 at 12:55AM

    As I understand it, AS::BufferedLogger was introduced for performance reasons, replacing it with your non-buffered logger might non be wise for production.

    There is further discussion here:

Comment How to get timestamps in your ruby on rails logs

Trackbacks are disabled

Powered by Typo – Thème Frédéric de Villamil | Photo Glenn