Sha256: 6f454a83608a19867ce0b1a026af67ca92b53daee0368e6579a9364bc4500cd8

Contents?: true

Size: 1.92 KB

Versions: 11

Compression:

Stored size: 1.92 KB

Contents

# typed: false

# Copyright (c) 2015 Sqreen. All Rights Reserved.
# Please refer to our terms for more information: https://www.sqreen.com/terms.html

require 'singleton'
require 'logger'
require 'sqreen/logger'

module Sqreen
  class DeferredLogger
    MAX_ENTRIES = 1000

    Entry = Struct.new(:severity, :message)

    def initialize
      @buffer = StringIO.new
      @logger = ::Logger.new(@buffer)
      @entries = []
      @mutex = Mutex.new
    end

    def debug?
      true
    end

    def info?
      true
    end

    def warn?
      true
    end

    def error?
      true
    end

    def fatal?
      true
    end

    def debug(msg = nil, &block)
      add(::Logger::DEBUG, msg, &block)
    end

    def info(msg = nil, &block)
      add(::Logger::INFO, msg, &block)
    end

    def warn(msg = nil, &block)
      add(::Logger::WARN, msg, &block)
    end

    def error(msg = nil, &block)
      add(::Logger::ERROR, msg, &block)
    end

    def fatal(msg = nil, &block)
      add(::Logger::FATAL, msg, &block)
    end

    def unknown(msg = nil, &block)
      add(::Logger::UNKNOWN, msg, &block)
    end

    def add(severity, msg = nil, &block)
      @mutex.synchronize do
        @entries.shift if @entries.count >= MAX_ENTRIES
        mark = @buffer.pos
        @logger.add(severity, msg, &block)
        @buffer.seek(mark)
        @entries << Entry.new(severity, @buffer.read)
        @buffer.truncate(0)
      end
    end

    def formatter=(value)
      @logger.formatter = value
    end

    def flush_to(logger)
      @mutex.synchronize do
        @entries.each do |entry|
          next if entry.severity < logger.level
          logger.instance_eval { @logdev }.write(entry.message)
        end
        reset
      end
    end

    private

    def reset
      buffer = StringIO.new
      logger = ::Logger.new(buffer)
      logger.formatter = @logger.formatter
      @buffer, @logger, @entries = buffer, logger, []
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
sqreen-1.22.0-java lib/sqreen/deferred_logger.rb
sqreen-1.22.0 lib/sqreen/deferred_logger.rb
sqreen-1.21.1-java lib/sqreen/deferred_logger.rb
sqreen-1.21.1 lib/sqreen/deferred_logger.rb
sqreen-1.21.0-java lib/sqreen/deferred_logger.rb
sqreen-1.21.0 lib/sqreen/deferred_logger.rb
sqreen-1.20.4-java lib/sqreen/deferred_logger.rb
sqreen-1.20.4 lib/sqreen/deferred_logger.rb
sqreen-1.21.0.beta3-java lib/sqreen/deferred_logger.rb
sqreen-1.21.0.beta3 lib/sqreen/deferred_logger.rb
sqreen-1.20.4.beta1 lib/sqreen/deferred_logger.rb