Sha256: 6e7d3bc7ce797728bdd0794057ba033fad324a52aa3b07da6e8125db0eecf241

Contents?: true

Size: 1.57 KB

Versions: 2

Compression:

Stored size: 1.57 KB

Contents

# frozen_string_literal: true

require 'logger'
require 'colorize'
require 'json'

module UU
  class LoggerStderr < Logger
    class Formatter
      DECORATION = {
        'UNKNOWN' => { color: :red, mode: :underline },
        'FATAL' => { color: :red, mode: :underline },
        'ERROR' => :red,
        'WARN' => :yellow,
        'INFO' => :default,
        'DEBUG' => :light_black,
      }.freeze

      def initialize(context)
        @context = context
      end

      attr_reader :context

      def call(severity, time, _progname, msg)
        loc = meaningful_location
        short_severity = severity[0, 1]
        time_format = time.utc.strftime('%T')
        context = @context.context
        context_msg = context.empty? ? '' : "#{context.to_json} "

        "#{short_severity}]#{time_format}" \
          "[#{loc[:filename]}##{loc[:method]}:#{loc[:lineno]}] " \
          "#{context_msg}" \
          "#{msg}\n".colorize(DECORATION[severity])
      end

      def meaningful_location
        location = find_location
        {
          filename: File.basename(location.path),
          method: location.label,
          lineno: location.lineno,
        }
      end

      PATHS = %w[
        /log.rb
        /logger.rb
        /loggable.rb
        /forwardable.rb
      ].freeze

      def find_location
        caller_locations.find do |location_|
          location_.path != __FILE__ &&
            PATHS.none? { |path| location_.path.end_with?(path) }
        end
      end
    end

    def initialize(context)
      super($stderr, formatter: Formatter.new(context))
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
uu-0.2.1 lib/uu/logger_stderr.rb
uu-0.2.0 lib/uu/logger_stderr.rb