Class: Lug::TtyDevice

Inherits:
Device
  • Object
show all
Includes:
Standard::TtyDeviceMethods
Defined in:
lib/lug/logger.rb

Overview

Logger class for tty IO devices

Output is colorized with standard ANSI escape codes

Constant Summary collapse

NS_COLORS =
[
  Colors::LIGHT_CYAN,
  Colors::LIGHT_GREEN,
  Colors::LIGHT_YELLOW,
  Colors::LIGHT_BLUE,
  Colors::LIGHT_MAGENTA,
  Colors::LIGHT_CYAN,
  Colors::LIGHT_RED,
  Colors::CYAN,
  Colors::GREEN,
  Colors::YELLOW,
  Colors::BLUE,
  Colors::MAGENTA,
  Colors::CYAN,
  Colors::RED
].freeze
MSG_COLOR =
Colors::WHITE

Instance Attribute Summary

Attributes inherited from Device

#io

Attributes included from Standard::DeviceMethods

#level_threshold

Instance Method Summary collapse

Methods inherited from Device

#enable, #enabled_for?, #on

Methods included from Standard::LoggerDeviceMethods

#debug, #error, #fatal, #info, #unknown, #warn

Constructor Details

#initialize(io = STDERR) ⇒ TtyDevice

Create a TtyDevice associated to an io instance

Parameters:

  • io (IO) (defaults to: STDERR)

    (default: STDERR)



222
223
224
225
226
227
# File 'lib/lug/logger.rb', line 222

def initialize(io = STDERR)
  super(io)
  @mutex = Mutex.new
  @prev_time = nil
  @colored_namespaces = {}
end

Instance Method Details

#log(message, namespace = nil) ⇒ NilClass

Log a message to output device, within a namespace

If IO device is a TTY, it will print namespaces with different ANSI colors to make them easily distinguishable.

Parameters:

  • message (String)
  • namespace (String, Symbol) (defaults to: nil)

    (default: nil)

Returns:

  • (NilClass)


238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/lug/logger.rb', line 238

def log(message, namespace = nil)
  @mutex.synchronize do
    now = Time.now
    line = [
      namespace && colorize_namespace(namespace),
      colorize(message, MSG_COLOR),
      elapsed_text(now)
    ].compact.join(' '.freeze)
    @prev_time = now

    @io.write("#{line}\n")
  end
  nil
end