Sha256: bd6c318c15b6b17831bc31bf4240290df7ddc11ebf4c1f5b3b42fde435b81337

Contents?: true

Size: 1.99 KB

Versions: 2

Compression:

Stored size: 1.99 KB

Contents

require 'rundock'
require 'logger'
require 'ansi/code'

module Rundock
  module Logger
    class Formatter
      attr_accessor :colored
      attr_accessor :indent_depth
      attr_accessor :color

      def initialize(*args)
        super
        @indent_depth = 0
      end

      def call(severity, datetime, progname, msg)
        out = "[%5s:] %s%s\n" % [severity, ' ' * 2 * indent_depth, msg2str(msg)]
        if colored
          colorize(out, severity)
        else
          out
        end
      end

      def indent
        add_indent
        yield
      ensure
        reduce_indent
      end

      def add_indent
        @indent_depth += 1
      end

      def reduce_indent
        @indent_depth -= 1 if @indent_depth > 0
      end

      def color(code)
        prev_color = @color
        @color = code
        yield
      ensure
        @color = prev_color
      end

      private

      def msg2str(msg)
        case msg
        when ::String
          msg
        when ::Exception
          "#{msg.message} (#{msg.class})\n" << (msg.backtrace || []).join("\n")
        else
          msg.inspect
        end
      end

      def colorize(msg, severity)
        if @color
          col = @color
        else
          col = case severity
                when 'INFO'
                  :clear
                when 'WARN'
                  :yellow
                when 'ERROR'
                  :red
                else
                  :clear
                end
        end

        ANSI.public_send(col) { msg }
      end
    end

    class << self
      def logger
        @logger ||= create_logger
      end

      private

      def create_logger
        ::Logger.new($stdout).tap do |logger|
          logger.formatter = Formatter.new
        end
      end

      private

      def respond_to_missing?(method, include_private = false)
        logger.respond_to?(method)
      end

      def method_missing(method, *args, &block)
        logger.public_send(method, *args, &block)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rundock-0.2.0 lib/rundock/logger.rb
rundock-0.1.0 lib/rundock/logger.rb