Sha256: c187c09a58032a05c0bbfd6a774b06e8dbf5da432454f0e1031fd9301ffeba35

Contents?: true

Size: 1.58 KB

Versions: 9

Compression:

Stored size: 1.58 KB

Contents

# frozen_string_literal: true

module Discorb
  # @private
  class Logger
    attr_accessor :out, :colorize_log

    @levels = %i[debug info warn error fatal].freeze

    def initialize(out, colorize_log, level)
      @out = out
      @level = self.class.levels.index(level)
      @colorize_log = colorize_log
    end

    def level
      self.class.levels[@level]
    end

    def level=(level)
      @level = self.class.levels.index(level)
      raise ArgumentError, "Invalid log level: #{level}" unless @level
    end

    def debug(message, fallback: nil)
      return unless @level <= 0

      write_output("DEBUG", "\e[90m", message, fallback)
    end

    def info(message, fallback: nil)
      return unless @level <= 1

      write_output("INFO", "\e[94m", message, fallback)
    end

    def warn(message, fallback: nil)
      return unless @level <= 2

      write_output("WARN", "\e[93m", message, fallback)
    end

    def error(message, fallback: nil)
      return unless @level <= 3

      write_output("ERROR", "\e[31m", message, fallback)
    end

    def fatal(message, fallback: nil)
      return unless @level <= 4

      write_output("FATAL", "\e[91m", message, fallback)
    end

    class << self
      attr_reader :levels
    end

    private

    def write_output(name, color, message, fallback)
      unless @out
        fallback.puts(message) if fallback

        return
      end

      if @colorize_log
        @out.puts("\e[2;90m[#{Time.now.iso8601}] #{color}#{name}\e[m -- #{message}")
      else
        @out.puts("[#{Time.now.iso8601}] #{name} -- #{message}")
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
discorb-0.11.1 lib/discorb/log.rb
discorb-0.11.0 lib/discorb/log.rb
discorb-0.10.3 lib/discorb/log.rb
discorb-0.10.2 lib/discorb/log.rb
discorb-0.10.1 lib/discorb/log.rb
discorb-0.10.0 lib/discorb/log.rb
discorb-0.9.6 lib/discorb/log.rb
discorb-0.9.5 lib/discorb/log.rb
discorb-0.9.4 lib/discorb/log.rb