Rails Own Logger

On July 16, 2011, in Uncategorized, by tov

I was in need of a logging mechanism that prints all log messages with a “severity” that equals or is higher of “INFO” to STDOUT (I’m using multilog for actual logging stuff).

As I wasn’t able to google a solution I came up with the following (not quite elaborated) code:

 

class OwnLogger < Logger

    include Severity
    SEV_LABEL = %w(DEBUG INFO WARN ERROR FATAL ANY)

    def add(severity, message = nil, progname = nil, &block)
      time = Time.now
      if ENV['LOG_FROM_INFO_TO_STDOUT']
        if severity >= INFO
          msg = "#{$$}:#{SEV_LABEL[severity]}:" + time.strftime("%Y-%m-%dT%H:%M:%S.") << "%06d " % time.usec + ":"
          if message.nil?
            if block_given?
              message = yield
            else
              message = progname
              progname = @progname

            end
            msg += message.to_s
            puts msg
          end
        end
        super
      end

    end

So if you put the following lines in your /config/application.rb you’ll get what I got :-)

config.logger = OwnLogger.new(File.dirname(__FILE__) + "/../log/#{ENV['PROCNAME']}#{Rails.env}.log")

AND (most important) you’ll still have the “normal” logfile containing all messages