sobota, 28 maja 2011

Ruby: Logging to STDOUT and file using standard ruby Logger

Have you ever wanted to log the message from your application to both standard output and file? If you have and you are using in your application the Logger that comes together with Ruby this article will be helpful for you.

First of all the description of the Logger can be found in the rdoc (http://www.ruby-doc.org/stdlib/libdoc/logger/rdoc/). Some of the features are listed below:
  • logging on multiple levels: FATAL, ERROR, WARNING, INFO, DEBUG
  • logging to a user defined device
  • custom formatting
But it does not provide functionalities similar to log4j like appenders, categories etc. (if you would like to use these the logging gem will be helpful: http://logging.rubyforge.org/).

The standard ruby Logger unfortunately does not provide functionality to log to multiple devices out of the box. In my opinion the simplest approach is to define an extension to the Logger like the one below (actually this can be used by you 1:1).

require 'logger'
class EnhancedLogger < Logger

  def initialize(logdev, shift_age = 10, shift_size = 1048576)
    super(logdev, shift_age, shift_size)
    @stdout = nil
    if (logdev == STDOUT)
      @stdout = STDOUT
    end
  end

  def logStd(severity, message = nil, progname = nil, &block)
    msg = format_message(format_severity(severity), Time.now, progname, message)
    self<<(msg)
    if (@stdout != nil)
      @stdout.puts(msg)
    end
  end
end


The EnhancedLogger class extends the standard Logger with an additional function called logStd, which in addition to the standard log device defined in the constructor displays the message also on the STDOUT. One can also think about similar function for STDERR (if required of course).

Brak komentarzy:

Prześlij komentarz