Sha256: e2c79141d305b273fd7a9ceaca23e927bec1beb97107d54fe02bc9c771ab6c5e

Contents?: true

Size: 1.94 KB

Versions: 1

Compression:

Stored size: 1.94 KB

Contents

module Eco
  module Language
    # Basic logger to format messaging to console
    class BasicLogger
      class << self
        def forward(*meths)
          meths.each do |meth|
            define_method(meth) do |*args, **kargs, &block|
              forward(meth, *args, **kargs, &block)
            end
          end
        end
      end

      TIMESTAMP_PATTERN = '%Y-%m-%dT%H:%M:%S'.freeze
      LOG_LEVELS = %i[unknown fatal error warn info debug].freeze
      METHODS    = %i[<< close add].freeze

      attr_writer :timestamp
      attr_reader :level

      forward(*LOG_LEVELS, *METHODS)

      def initialize(level: ::Logger::INFO, timestamp: false)
        @level             = level
        self.timestamp     = timestamp

        loggers[:console]  = ::Logger.new($stdout).tap do |logger|
          logger.formatter = format_proc(console: true)
          logger.level     = level
        end
      end

      def timestamp?
        @timestamp
      end

      def level=(value)
        loggers[:console].level = value
      end

      private

      def forward(meth, *args, &block)
        loggers.each_value do |logger|
          logger.send(meth, *args, &block)
        end
      end

      def loggers
        @loggers ||= {}
      end

      def console_timestamp(datetime)
        return unless timestamp?

        timestamp(datetime)
      end

      def timestamp(datetime)
        return unless datetime

        str_date = datetime.strftime(self.class::TIMESTAMP_PATTERN)
        "#{str_date} > "
      end

      def format_proc(console: true, &block)
        proc do |severity, datetime, _progname, msg|
          str_stamp = console ? console_timestamp(datetime) : timestamp(datetime)

          "#{severity.to_s[0]}: #{str_stamp}#{msg}\n".tap do |formatted_msg|
            block&.call(severity, datetime, msg, formatted_msg)
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
eco-helpers-3.0.21 lib/eco/language/basic_logger.rb