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 Initializer.run block:
config.logger = Logger.new(File.dirname(__FILE__) + "/../log/#{RAILS_ENV}.log")
config.logger.formatter = Logger::Formatter.newThen in development.rb, test.rb and production.rb:
config.logger.level = Logger::DEBUGYou 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
endPosted in Ruby on Rails | 1 comment |
about 1 year later:
Thanks Miles … just what I needed