Class: Util::ConsoleLogger

Inherits:
Object
  • Object
show all
Defined in:
lib/util/console_logger.rb

Overview

Help write formatted messages to the console, for friendlier command-line interface. Uses generally available ANSI codes, so it should work on all UNIXes and on recent Windows.

Examples:

cl = ConsoleLogger.new e: { :stderr => true }
cl.warning 'Errors will be logged on STDERR.'
  # Message written in yellow
begin
  text = File.read 'secret.msg'
rescue Exception => e
  msg = 'Cannot go any further because of %E%, aborting.'
  cl.error msg, 'E': e.message
    # Message written in red
end

Constant Summary collapse

RESET =

ANSI code to reset all formatting

"\x1b[0m"
BASE =

Do not document:

"\x1b[%CODE%m"
COLORS =

Do not document:

{ :black => 0, :red => 1, :green => 2, :yellow => 3,
:blue => 4, :magenta => 5, :cyan => 6, :white => 7 }
COLOR_TYPES =

Do not document:

{ :fg => 30, :bg => 40, :bright => 60 }
DECORS =

Do not document:

{ :bold => 1, :faint => 2, :italic => 3, :underline => 4,
:blink => 5, :reverse => 7, :conceal => 8, :crossed => 9,
:dbl_underline => 21, :overline => 53 }
CL =

Do not document:

ConsoleLogger

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ ConsoleLogger

Create a new ConsoleLogger.

Parameters:

  • config (Hash) (defaults to: {})

    initial configuration: for each kind of message, whether to use STDERR or STDOUT, and which formatting

Options Hash (config):

  • e (Hash { :stderr => Boolean, :code => String })

    configuration for error (defaults to red text)

  • i (Hash { :stderr => Boolean, :code => String })

    configuration for information (defaults to cyan text)

  • n (Hash { :stderr => Boolean, :code => String })

    configuration for normal (defaults to no formatting)

  • o (Hash { :stderr => Boolean, :code => String })

    configuration for ok (defaults to green text)

  • w (Hash { :stderr => Boolean, :code => String })

    configuration for warning (defaults to yellow text)



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/util/console_logger.rb', line 98

def initialize config={}
  config = Arg.check config, Hash, {}
  @config = {
    :e => { :io => $stdout, :code => CL.escape_code(color: :red) },
    :i => { :io => $stdout, :code => CL.escape_code(color: :cyan) },
    :n => { :io => $stdout, :code => '' },
    :o => { :io => $stdout, :code => CL.escape_code(color: :green) },
    :w => { :io => $stdout, :code => CL.escape_code(color: :yellow) },
  }

  config.each_pair do |k, v|
    next unless @config.has_key? k
    v = Arg.check v, Hash, {}
    @config[k][:io] = (v[:stderr] == true) ? $stderr : $stdout
    @config[k][:code] = CL.escape_code v
  end
end

Class Method Details

.escape_code(opts = {}) ⇒ Object

Generate the ANSI code to obtain a given formatting.

Parameters:

  • opts (Hash) (defaults to: {})

    the wanted formatting

Options Hash (opts):

  • :color (:black, :blue, :cyan, :green, :magenta, :red, :white, :yellow)

    font color

  • :bgcolor (idem)

    background color

  • :bright (Boolean)

    use bright font color

  • :bgbright (Boolean)

    use bright background color

  • :decor (:blink, :bold, :conceal, :crossed, :dbl_underline, :faint, :italic, :overline, :reverse, :underline, Array<idem>)

    text decorations



46
47
48
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
# File 'lib/util/console_logger.rb', line 46

def self.escape_code opts={}
  opts = Arg.check opts, Hash, {}
  return RESET if opts.empty?
  code = ''

  if opts.has_key? :color then
    color = Arg.check opts[:color], Symbol, :white
    color = :white unless COLORS.has_key? color
    bright = Arg.check opts[:bright], 'Boolean', false

    cur = COLOR_TYPES[:fg] + COLORS[color]
    cur += COLOR_TYPES[:bright] if bright
    code += cur.to_s
  end

  if opts.has_key? :bgcolor then
    color = Arg.check opts[:bgcolor], Symbol, :black
    color = :black unless COLORS.has_key? color
    bright = Arg.check opts[:bgbright], 'Boolean', false

    cur = COLOR_TYPES[:bg] + COLORS[color]
    cur += COLOR_TYPES[:bright] if bright
    code += ';' unless code.empty?
    code += cur.to_s
  end

  if opts.has_key? :decor then
    decors = Arg.check opts[:decor], Array, [opts[:decor]]
    cur = ''
    decors.each do |d|
      cur += ';' + DECORS[d].to_s if DECORS.has_key? d
    end
    cur = cur.sub ';', '' if code.empty?
    code += cur
  end

  code.empty? ? RESET : BASE.sub('%CODE%', code)
end

Instance Method Details

#error(msg, payload = {}) ⇒ Object

Print an error to the console.

Examples:

msg = 'The array contains only %I% objects of type %T%.'
cl.error msg, 'T': Float, 'I': arr.how_many?(Float)

# Results in `The array contains only 42 objects of type Float.`

Parameters:

  • msg (String)

    message to print

  • payload (Hash<#to_s, #to_s>) (defaults to: {})

    parts to replace in the base message: ‘%KEY%’ will be replaced by ‘VALUE’.

Returns:

  • nil



126
127
128
# File 'lib/util/console_logger.rb', line 126

def error msg, payload={}
  self.printf :e, msg, payload
end

#important(msg, payload = {}) ⇒ Object

Print an important message to the console.

Examples:

msg = 'The array contains only %I% objects of type %T%.'
cl.error msg, 'T': Float, 'I': arr.how_many?(Float)

# Results in `The array contains only 42 objects of type Float.`

Parameters:

  • msg (String)

    message to print

  • payload (Hash<#to_s, #to_s>) (defaults to: {})

    parts to replace in the base message: ‘%KEY%’ will be replaced by ‘VALUE’.

Returns:

  • nil



134
135
136
# File 'lib/util/console_logger.rb', line 134

def important msg, payload={}
  self.printf :i, msg, payload
end

#normal(msg, payload = {}) ⇒ Object

Print a normal message to the console.

Examples:

msg = 'The array contains only %I% objects of type %T%.'
cl.error msg, 'T': Float, 'I': arr.how_many?(Float)

# Results in `The array contains only 42 objects of type Float.`

Parameters:

  • msg (String)

    message to print

  • payload (Hash<#to_s, #to_s>) (defaults to: {})

    parts to replace in the base message: ‘%KEY%’ will be replaced by ‘VALUE’.

Returns:

  • nil



142
143
144
# File 'lib/util/console_logger.rb', line 142

def normal msg, payload={}
  self.printf :n, msg, payload
end

#ok(msg, payload = {}) ⇒ Object

Print an approval to the console.

Examples:

msg = 'The array contains only %I% objects of type %T%.'
cl.error msg, 'T': Float, 'I': arr.how_many?(Float)

# Results in `The array contains only 42 objects of type Float.`

Parameters:

  • msg (String)

    message to print

  • payload (Hash<#to_s, #to_s>) (defaults to: {})

    parts to replace in the base message: ‘%KEY%’ will be replaced by ‘VALUE’.

Returns:

  • nil



150
151
152
# File 'lib/util/console_logger.rb', line 150

def ok msg, payload={}
  self.printf :o, msg, payload
end

#warning(msg, payload = {}) ⇒ Object

Print a warning to the console.

Examples:

msg = 'The array contains only %I% objects of type %T%.'
cl.error msg, 'T': Float, 'I': arr.how_many?(Float)

# Results in `The array contains only 42 objects of type Float.`

Parameters:

  • msg (String)

    message to print

  • payload (Hash<#to_s, #to_s>) (defaults to: {})

    parts to replace in the base message: ‘%KEY%’ will be replaced by ‘VALUE’.

Returns:

  • nil



158
159
160
# File 'lib/util/console_logger.rb', line 158

def warning msg, payload={}
  self.printf :w, msg, payload
end