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

Attributes included from Equatable

#comparison_attrs

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Equatable

#attr_reader, included, #inherited

Constructor Details

#initialize(options = {}) ⇒ Logger

Initialize a Logger

Parameters:

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

Options Hash (options):

  • :output (String)


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

def initialize(options={})
  @namespace = options.fetch(:namespace) { raise ArgumentError, "Logger must have namespace", caller }
  @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.



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

def level
  @level
end

#namespaceObject (readonly)

Returns the value of attribute namespace.



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

def namespace
  @namespace
end

#outputObject (readonly)

Returns the value of attribute output.



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

def output
  @output
end

#timestamp_formatObject (readonly)

Returns the value of attribute timestamp_format.



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

def timestamp_format
  @timestamp_format
end

Class Method Details

.valid_level?(level) ⇒ Boolean

Returns:

  • (Boolean)


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

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

Instance Method Details

#log(message) ⇒ Object

Print formatted log to output



66
67
68
# File 'lib/tty/logger.rb', line 66

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

#timestampObject



49
50
51
# File 'lib/tty/logger.rb', line 49

def timestamp
  Time.now.strftime(timestamp_format)
end

#validate_level(level) ⇒ Object



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

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