Sha256: 340d64b60d633616d8ff034c4d640e41ea6ea862949b5d3ec3b072910e340b8f

Contents?: true

Size: 1.21 KB

Versions: 1

Compression:

Stored size: 1.21 KB

Contents

module Spanx
  module Logger

    class << self
      def enable
        class << self
          self.send(:define_method, :log, proc { |msg| _log(msg) })
          self.send(:define_method, :logging, proc { |msg, &block| _logging(msg, &block) })
        end
      end

      def disable
        class << self
          self.send(:define_method, :log, proc { |msg|})
          self.send(:define_method, :logging, proc { |msg, &block| block.call })
        end
      end

      def log(msg)
      end

      def logging(msg, &block)
        block.call
      end

      private

      def _log(msg)
        puts "#{Time.now}: #{sprintf("%-20s", Thread.current[:name])} - #{msg}"
      end

      def _logging(message, &block)
        start = Time.now
        returned_from_block = yield
        elapsed_time = Time.now - start
        if returned_from_block.is_a?(String) && returned_from_block != ""
          message += " - #{returned_from_block}"
        end
        log "(#{"%9.2f" % (1000 * elapsed_time)}ms) #{message}"
        returned_from_block
      rescue StandardError => e
        elapsed_time = Time.now - start
        log "(#{"%9.2f" % (1000 * elapsed_time)}ms) error: #{e.message} for #{message} "
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
spanx-0.3.0 lib/spanx/logger.rb