log4r and Gateway pattern

Finally, I’m tired of adding and removing puts, pp, print, … etc in my ruby code, and decided to go to log4r.

With log4net experience, it makes sense to apply the same gateway pattern in log4r, so my usage of log4r syntax should look like:

Logger.for(self).debug(msg)

Here is my code:

require 'log4r'
include Log4r

class MyLogger

  def self.for(obj)
    Logger[obj.class.name] || self.create_logger_for(obj.class.name)
  end

  private

  def self.create_logger_for(key)
    mylog =  Logger.new(key)

    mylog.level = $DEBUG ? DEBUG : INFO

    mylog.add Outputter.stdout

    file_format = PatternFormatter.new(:pattern => "[ %d ] %l\t %C %m")
    mylog.add FileOutputter.new("fileOutputter_for_#{key}", :filename => "./log/#{key}.log", :formatter=>file_format)
    mylog
  end

end

Calling ruby with -d parm can run in Debug mode, and $DEBUG global variable is the catcher.

Advertisements