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:


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)


  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)


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


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s