Class: Zephira::Logger

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

Constant Summary collapse

LOG_LEVELS =
%i[debug info warn error].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path:, log_level: :debug) ⇒ Logger

Returns a new instance of Logger.

Raises:

  • (ArgumentError)


11
12
13
14
15
16
17
# File 'lib/zephira/logger.rb', line 11

def initialize(file_path:, log_level: :debug)
  FileUtils.mkdir_p(File.dirname(file_path))
  @logfile = File.open(file_path, "a")
  @log_level = log_level

  raise ArgumentError, "Invalid log level: #{log_level}" unless LOG_LEVELS.include?(log_level)
end

Instance Attribute Details

#log_levelObject (readonly)

Returns the value of attribute log_level.



9
10
11
# File 'lib/zephira/logger.rb', line 9

def log_level
  @log_level
end

#logfileObject (readonly)

Returns the value of attribute logfile.



9
10
11
# File 'lib/zephira/logger.rb', line 9

def logfile
  @logfile
end

Instance Method Details

#debug(message, **args) ⇒ Object



19
20
21
# File 'lib/zephira/logger.rb', line 19

def debug(message, **args)
  log(:debug, message, **args)
end

#error(message, **args) ⇒ Object



27
28
29
# File 'lib/zephira/logger.rb', line 27

def error(message, **args)
  log(:error, message, **args)
end

#info(message, **args) ⇒ Object



23
24
25
# File 'lib/zephira/logger.rb', line 23

def info(message, **args)
  log(:info, message, **args)
end

#log(level, message, **args) ⇒ Object



35
36
37
38
39
40
# File 'lib/zephira/logger.rb', line 35

def log(level, message, **args)
  return unless should_log?(level)

  @logfile.puts "#{Time.now} - #{level.to_s.strip.upcase} - #{message} - #{args.inspect}"
  @logfile.flush
end

#should_log?(level) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
# File 'lib/zephira/logger.rb', line 42

def should_log?(level)
  LOG_LEVELS.index(level) >= LOG_LEVELS.index(@log_level)
end

#warn(message, **args) ⇒ Object



31
32
33
# File 'lib/zephira/logger.rb', line 31

def warn(message, **args)
  log(:warn, message, **args)
end