Module: CliUI::Loggable

Defined in:
lib/cli_ui/loggable.rb

Overview

Handle application log

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Class Attribute Details

.levelObject

Log output level. Can be one of Logger::DEBUG, Logger::INFO, Logger::WARN, Logger::ERROR



35
36
37
# File 'lib/cli_ui/loggable.rb', line 35

def level
  @level
end

.log_pathObject

Path in which log files are saved ( default STDOUT )



35
# File 'lib/cli_ui/loggable.rb', line 35

attr_accessor :level, :log_path

Class Method Details

.configure_logger_for(classname) ⇒ Object

Create and configure a logger for the specified Class

Parameters:

  • classname (String)

    the name of the class for which a logger instance must be retrieved

Returns:

  • (Object)

    the instance of the logger class for the specified Class



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/cli_ui/loggable.rb', line 49

def configure_logger_for(classname)
  # handle case in which log path does not exists
  begin
    logger = Logger.new(@log_path)
  rescue Errno::ENOENT
    FileUtils.mkdir_p File.dirname @log_path
    retry
  end

  logger.progname = classname
  logger.level = @level
  logger.formatter = proc { |severity, datetime, progname, msg|
    case severity
    when 'DEBUG'
      spaciator = "    *"
      after_space = ""
    when 'INFO'
      spaciator = "   **"
      after_space = " "
    when 'WARN'
      spaciator = "  ***"
      after_space = " "
    when 'ERROR'
      spaciator = " ****"
      after_space = ""
    when 'FATAL'
      spaciator = "*****"
      after_space = ""
    else
      spaciator = "     "
      after_space = ""
    end

    formatted_output = " #{spaciator} [#{severity}]#{after_space} [#{datetime}] -- #{msg} { #{progname} }\n"
    formatted_output
  }
  logger
end

.logger_for(classname) ⇒ Object

Return the logger for a specific Class. If the instance is not found, creates it.

Parameters:

  • classname (String)

    the name of the class for which a logger instance must be retrieved

Returns:

  • (Object)

    the instance of the logger class for the specified Class



41
42
43
# File 'lib/cli_ui/loggable.rb', line 41

def logger_for(classname)
  @loggers[classname] ||= configure_logger_for(classname)
end

Instance Method Details

#loggerObject

Global, memoized, lazy initialized instance of a logger

This is the magical bit that gets mixed into your classes. Respond to Logger function.

Returns:

  • (Object)

    an instance of the logger class



25
26
27
28
# File 'lib/cli_ui/loggable.rb', line 25

def logger
  classname = (self.is_a? Module) ? self : self.class.name
  @logger ||= Loggable.logger_for(classname)
end