Sha256: cbd0da3cdabb80caec5900109c63e859c17886589dbd7c78490b303be0b4e214

Contents?: true

Size: 1.86 KB

Versions: 33

Compression:

Stored size: 1.86 KB

Contents

require 'itamae'
require 'logger'
require 'ansi/code'

module Itamae
  module Logger
    class Formatter
      attr_accessor :colored
      attr_accessor :depth

      INDENT_LENGTH = 3

      def initialize(*args)
        super

        @depth = 0
      end

      def call(severity, datetime, progname, msg)
        log = "%s : %s%s\n" % ["%5s" % severity, ' ' * INDENT_LENGTH * depth , msg2str(msg)]
        if colored
          color(log, severity)
        else
          log
        end
      end

      def indent
        @depth += 1
        yield
      ensure
        @depth -= 1
      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 color(str, severity)
        color_code = case severity
                     when "INFO"
                       :green
                     when "WARN"
                       :magenta
                     when "ERROR"
                       :red
                     else
                       :clear
                     end
        ANSI.public_send(color_code) { str }
      end
    end

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

      def log_device
        @log_device || $stdout
      end

      def log_device=(value)
        @log_device = value
        @logger = create_logger
      end
      
      private

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

      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

33 entries across 33 versions & 1 rubygems

Version Path
itamae-1.1.7 lib/itamae/logger.rb
itamae-1.1.5 lib/itamae/logger.rb
itamae-1.1.4 lib/itamae/logger.rb
itamae-1.1.3 lib/itamae/logger.rb
itamae-1.1.2 lib/itamae/logger.rb
itamae-1.1.1 lib/itamae/logger.rb
itamae-1.1.0 lib/itamae/logger.rb
itamae-1.0.13 lib/itamae/logger.rb
itamae-1.0.12 lib/itamae/logger.rb
itamae-1.0.11 lib/itamae/logger.rb
itamae-1.0.10 lib/itamae/logger.rb
itamae-1.0.9 lib/itamae/logger.rb
itamae-1.0.8 lib/itamae/logger.rb
itamae-1.0.7 lib/itamae/logger.rb
itamae-1.0.6 lib/itamae/logger.rb
itamae-1.0.5 lib/itamae/logger.rb
itamae-1.0.4 lib/itamae/logger.rb
itamae-1.0.3 lib/itamae/logger.rb
itamae-1.0.2 lib/itamae/logger.rb
itamae-1.0.1 lib/itamae/logger.rb