Class: TTY::Logger

Inherits:
Object
  • Object
show all
Includes:
Equatable
Defined in:
lib/tty/logger.rb

Overview

A class providing logging system

Constant Summary collapse

ALL =
0
INFO =
1
DEBUG =
2
WARN =
3
ERROR =
4
FATAL =
5
OFF =
6
MAX_LEVELS =
7

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Logger

Initialize a Logger

Parameters:

  • name (String)
  • options (Hash) (defaults to: {})

Options Hash (options):

  • :output (String)


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

def initialize(options = {})
  @namespace = options.fetch(:namespace) do
    fail ArgumentError, 'Logger must have namespace', caller
  end
  @output = options.fetch(:output) { $stderr }
  @level  = options.fetch(:level) { ALL }
  @timestamp_format = options.fetch(:timestamp_format) { '%Y-%m-%d %T' }
end

Instance Attribute Details

#levelObject

Returns the value of attribute level.



20
21
22
# File 'lib/tty/logger.rb', line 20

def level
  @level
end

#namespaceObject (readonly)

Returns the value of attribute namespace.



18
19
20
# File 'lib/tty/logger.rb', line 18

def namespace
  @namespace
end

#outputObject (readonly)

Returns the value of attribute output.



22
23
24
# File 'lib/tty/logger.rb', line 22

def output
  @output
end

#timestamp_formatObject (readonly)

Returns the value of attribute timestamp_format.



24
25
26
# File 'lib/tty/logger.rb', line 24

def timestamp_format
  @timestamp_format
end

Class Method Details

.valid_level?(level) ⇒ Boolean

Verify valid level

Parameters:

  • level (Number)

    the level of this logger

Returns:

  • (Boolean)


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

def self.valid_level?(level)
  !level.nil? && level.is_a?(Numeric) && level >= ALL && level <= OFF
end

Instance Method Details

#log(message) ⇒ Object

Print formatted log to output

Parameters:

  • message (String)

    the message to print to output



81
82
83
# File 'lib/tty/logger.rb', line 81

def log(message)
  output.print timestamp + ' - ' + message
end

#timestampTime

Create a timestamp

Returns:

  • (Time)


54
55
56
# File 'lib/tty/logger.rb', line 54

def timestamp
  Time.now.strftime(timestamp_format)
end

#validate_level(level) ⇒ Object



58
59
60
61
# File 'lib/tty/logger.rb', line 58

def validate_level(level)
  return if valid_level?(level)
  fail ArgumentError, "Log level must be 0..#{MAX_LEVELS}", caller
end