Class: KeySloth::Logger

Inherits:
Object
  • Object
show all
Defined in:
lib/keysloth/logger.rb

Overview

Класс для многоуровневого логирования KeySloth

Обеспечивает логирование с различными уровнями детализации:

  • ERROR: только критические ошибки
  • INFO: основная информация о процессе (по умолчанию)
  • DEBUG: подробная отладочная информация

Examples:

Использование логгера

logger = KeySloth::Logger.new
logger.info("Начинаем операцию")
logger.debug("Подробная информация")
logger.error("Критическая ошибка")

Author:

  • KeySloth Team

Since:

  • 0.1.0

Instance Method Summary collapse

Constructor Details

#initialize(level: :info, output: $stdout) ⇒ Logger

Инициализация логгера

Parameters:

  • level (Symbol) (defaults to: :info) —

    Уровень логирования (:error, :info, :debug)

  • output (IO) (defaults to: $stdout) —

    Поток вывода (по умолчанию STDOUT)

Since:

  • 0.1.0



26
27
28
29
30
31
32
# File 'lib/keysloth/logger.rb', line 26

def initialize(level: :info, output: $stdout)
  @logger = ::Logger.new(output)
  @logger.level = log_level_constant(level)
  @logger.formatter = proc do |severity, datetime, _progname, msg|
    "[#{datetime.strftime('%Y-%m-%d %H:%M:%S')}] #{severity}: #{msg}\n"
  end
end

Instance Method Details

#audit(operation, details = {}) ⇒ Object

Аудит логирование для операций безопасности

Parameters:

  • operation (String) —

    Тип операции (pull, push, validate, etc.)

  • details (Hash) (defaults to: {}) —

    Детали операции

Since:

  • 0.1.0



86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/keysloth/logger.rb', line 86

def audit(operation, details = {})
  timestamp = Time.now.utc.strftime('%Y-%m-%d %H:%M:%S UTC')

  audit_message = "[AUDIT] #{timestamp} | Operation: #{operation}"

  # Добавляем детали если они есть
  unless details.empty?
    details_str = details.map { |k, v| "#{k}=#{sanitize_log_value(v, k)}" }.join(', ')
    audit_message += " | #{details_str}"
  end

  @logger.info(audit_message)
end

#debug(message) ⇒ Object

Логирование отладочных сообщений

Parameters:

  • message (String) —

    Сообщение для логирования

Since:

  • 0.1.0



44
45
46
# File 'lib/keysloth/logger.rb', line 44

def debug(message)
  @logger.debug(message)
end

#error(message, exception = nil) ⇒ Object

Логирование ошибок

Parameters:

  • message (String) —

    Сообщение об ошибке

  • exception (Exception, nil) (defaults to: nil) —

    Исключение для детального логирования (опционально)

Since:

  • 0.1.0



59
60
61
62
63
64
65
66
# File 'lib/keysloth/logger.rb', line 59

def error(message, exception = nil)
  if exception
    @logger.error("#{message}: #{exception.message}")
    @logger.debug("Backtrace: #{exception.backtrace.join("\n")}")
  else
    @logger.error(message)
  end
end

#info(message) ⇒ Object

Логирование информационных сообщений

Parameters:

  • message (String) —

    Сообщение для логирования

Since:

  • 0.1.0



37
38
39
# File 'lib/keysloth/logger.rb', line 37

def info(message)
  @logger.info(message)
end

#level ⇒ Integer

Возвращает текущий уровень логирования

Returns:

  • (Integer) —

    Константа уровня логирования

Since:

  • 0.1.0



78
79
80
# File 'lib/keysloth/logger.rb', line 78

def level
  @logger.level
end

#level=(level) ⇒ Object

Изменяет уровень логирования

Parameters:

  • level (Symbol) —

    Новый уровень логирования (:error, :info, :debug)

Since:

  • 0.1.0



71
72
73
# File 'lib/keysloth/logger.rb', line 71

def level=(level)
  @logger.level = log_level_constant(level)
end

#security_log(operation, result, duration: nil, details: {}) ⇒ Object

Логирование операций безопасности с метриками

Parameters:

  • operation (String) —

    Тип операции

  • result (Symbol) —

    Результат операции (:success, :failure, :warning)

  • duration (Float) (defaults to: nil) —

    Длительность операции в секундах (опционально)

  • details (Hash) (defaults to: {}) —

    Дополнительные детали

Since:

  • 0.1.0



106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/keysloth/logger.rb', line 106

def security_log(operation, result, duration: nil, details: {})
  level_method = case result
                 when :success then :info
                 when :failure then :error
                 when :warning then :warn
                 else :info
                 end

  message = "[SECURITY] #{operation.upcase}: #{result.to_s.upcase}"
  message += " (#{duration.round(2)}s)" if duration

  unless details.empty?
    details_str = details.map { |k, v| "#{k}=#{sanitize_log_value(v, k)}" }.join(', ')
    message += " | #{details_str}"
  end

  send(level_method, message)

  # Дублируем критические ошибки в аудит лог
  audit(operation, details.merge(result: result, duration: duration)) if result == :failure
end

#warn(message) ⇒ Object

Логирование предупреждений

Parameters:

  • message (String) —

    Сообщение для логирования

Since:

  • 0.1.0



51
52
53
# File 'lib/keysloth/logger.rb', line 51

def warn(message)
  @logger.warn(message)
end