everything and nothing

allskonar

Pimping ruby Logger instance

November 24th, 2009


# pimping loggin a bit 
LOG = Logger.new('logs/application.log')
%w(debug info warn error fatal).each do |level|
  eval <<-end_eval
    def LOG.#{level}(message="", &blk)
      if message == "" and block_given?
        message = blk.call
      end 
      file,line_number,method_name = caller.first.split(":")
      method_name = "" unless method_name
      filename = File.basename(file)
      super(filename + ":" + line_number) { method_name + " " + message }
    end 
  end_eval
end


I had to brag, it’s rare that I dabble in magic code i.e. code that is too clever to be understood right away and impossible to troubleshoot unless you wrote it yourself (recently). I usually try to keep my code quite simple. Clever has a bad rap in coding and for good reason since even the cleverest person can easily forget the lightning of cleverness that struck when he or she wrote something just a few weeks earlier. Even though clever code is bad it’s extremely satisfying when you solve something cleverly.

I am writing an application that operates mostly in the background i.e. without user interacting with it directly which makes troubleshooting tricky since one can’t easily throw in a debug statement and step through the code execution. I ofcourse have decent test coverage helps but in production code seems determinate to make once life miserable. This is where good logging becomes vital in chasing down bugs or performance bottlenecks in production code.

Logger in the standard ruby library is extremely awesome I have found that I just wanted a little more out of it namely I wanted by default a single log file with the name script file name, line number and perhaps the method name where a particular message was sent to the logger. There didn’t seem to be an automatic way of doing this so I resulted to do a little overwriting (the magic). I accomplished this by defining a singleton method on my logger instance.

Sorry, comments are closed for this article.

Freyja Channel


last.fm recent tracks

allskonar Powered by Mephisto