class Telegram::LoggerBot::Logger

Constants

SEV_ICON
TIME_ICON_FIRST_HALF
TIME_ICON_SECOND_HALF

Public Class Methods

new(args = {}) click to toggle source
# File lib/telegram/loggerbot/logger.rb, line 8
def initialize(args = {})
  args = args.dup
  @default_formatter = args.delete(:default_formatter) || Formatter.new

  @level = args.delete(:level) || Telegram::LoggerBot.configuration.level || DEBUG
  @chat_id = args.delete(:chat_id) || Telegram::LoggerBot.configuration.chat_id || fail(ChatIdMissed)
  @token = args.delete(:token) || Telegram::LoggerBot.configuration.token || fail(TokenMissed)
  @next_logger = args.delete(:next_logger) || Telegram::LoggerBot.configuration.next_logger
  @api = args.delete(:api) || Telegram::LoggerBot.configuration.api || Telegram::Bot::Api.new(@token)

  @enabled =
      if args.key?(:enabled)
        value = args.delete(:enabled)
        case value
          when true, false
            value
          else
            true
        end
      elsif not Telegram::LoggerBot.configuration.enabled.nil?
        !!Telegram::LoggerBot.configuration.enabled
      else
        true
      end

  fail(UnknownParams, args) if args.keys.size > 0
end

Public Instance Methods

add(severity, message = nil, progname = nil, &block) click to toggle source
# File lib/telegram/loggerbot/logger.rb, line 94
def add(severity, message = nil, progname = nil, &block)
  severity ||= UNKNOWN

  if severity < @level
    if @next_logger
      return @next_logger.add(severity, message, progname, &block)
    else
      return true
    end
  end

  if message.nil?
    if block_given?
      message = block.dup.call
    else
      message = progname
      progname = @progname
    end
  end

  if @enabled
    time = Time.now

    text = "#{format_severity_icon(severity)}*#{format_severity(severity)}*"
    text << "   _#{clear_markdown(progname)}_" if progname
    text << "\n#{format_time_icon(time)}#{time}"

    @api.send_message(chat_id: @chat_id, text: text, parse_mode: 'Markdown')
    @api.send_message(chat_id: @chat_id, text: message)
  end

  if @next_logger
    @next_logger.add(severity, message, progname, &block)
  else
    true
  end
end
clear_markdown(str) click to toggle source
# File lib/telegram/loggerbot/logger.rb, line 36
def clear_markdown(str)
  str.gsub(/[^a-zA-Z0-9\<\>\s\n:+-]/, '')
end
format_severity_icon(severity) click to toggle source
# File lib/telegram/loggerbot/logger.rb, line 49
def format_severity_icon(severity)
  SEV_ICON[severity] || "\xF0\x9F\x93\x93"
end
format_time_icon(time) click to toggle source
# File lib/telegram/loggerbot/logger.rb, line 83
def format_time_icon(time)
  hour12 = time.strftime('%I').to_i
  hour12 = 0 if hour12 == 12
  minute = time.strftime('%M').to_i
  if minute < 30
    TIME_ICON_FIRST_HALF[hour12]
  else
    TIME_ICON_SECOND_HALF[hour12]
  end
end