Sha256: 1376d44af299ab3a7cf93f30bfc19641de05ec45affb7e73c282ca31d74fb30f

Contents?: true

Size: 1.72 KB

Versions: 31

Compression:

Stored size: 1.72 KB

Contents

require 'logger'

class QueuedLogger < Logger
  def initialize(*args)
    super(*args)
    @queue = []
    @emitted = false
  end

  def process_queue
    if queued?
      while true
        entry = @queue.shift or break
        severity, message = entry
        raw_method = "#{severity}_without_queue"
        severity_i = self.class.send(:const_get, severity.to_s.upcase)
        send(raw_method, message)
      end
    end
  end

  def enqueue(level, message)
    @queue << [level, message]
    @emitted = false
  end

  def dequeue(level=nil, message=nil)
    if queued?
      @queue.clear
    elsif level and message
      send("%s_without_queue"%level, message) if @emitted
    end
    @emitted = false
  end

  def queued?
    ! @queue.empty?
  end

  for level in %w(debug info warn error fatal) do
    class_eval <<-EOB
      def #{level}_with_queue(*args)
        severity = self.class.send(:const_get, "#{level.upcase}")
        process_queue if severity >= self.level
        @emitted = true
        #{level}_without_queue(*args)
      end
      alias_method_chain :#{level}, :queue
    EOB
  end

end

if __FILE__ == $0
  # TODO QueuedLogger -- write a spec

  q = QueuedLogger.new($stdout)
  q.level = Logger::INFO
  q.info("first message")
  q.enqueue(:info, "queued message that'll be pushed")
  q.info("second message, which pushed out queued message")
  q.enqueue(:error, "ERROR: queued message that'll be discarded")
  q.debug("ERROR: message that'll be discarded and won't push queue")
  q.dequeue(:error, "ERROR: dequeue message that'll be discarded")
  q.enqueue(:info, "queued message that'll be pushed")
  q.info("message that'll push out the queue and dequeue messages")
  q.dequeue(:info, "dequeue message that'll be pushed")
end

Version data entries

31 entries across 31 versions & 2 rubygems

Version Path
automate-it-0.9.2 lib/queued_logger.rb
automate-it-0.9.1 lib/queued_logger.rb
automate-it-0.9.0 lib/queued_logger.rb
automateit-0.70923 lib/queued_logger.rb
automateit-0.70928 lib/queued_logger.rb
automateit-0.70930 lib/queued_logger.rb
automateit-0.71003 lib/queued_logger.rb
automateit-0.71017 lib/queued_logger.rb
automateit-0.71006 lib/queued_logger.rb
automateit-0.71012 lib/queued_logger.rb
automateit-0.71021 lib/queued_logger.rb
automateit-0.71031.1 lib/queued_logger.rb
automateit-0.71030 lib/queued_logger.rb
automateit-0.71031.2 lib/queued_logger.rb
automateit-0.71101.1 lib/queued_logger.rb
automateit-0.71101.2 lib/queued_logger.rb
automateit-0.71102 lib/queued_logger.rb
automateit-0.71103 lib/queued_logger.rb
automateit-0.71101 lib/queued_logger.rb
automateit-0.71031 lib/queued_logger.rb