class Lug::TtyDevice
Logger
class for tty IO devices
Output is colorized with standard ANSI escape codes
Constants
- MSG_COLOR
- NS_COLORS
Public Class Methods
Create a TtyDevice
associated to an io
instance
@param io [IO] (default: STDERR)
Lug::Device::new
# File lib/lug/logger.rb, line 222 def initialize(io = STDERR) super(io) @mutex = Mutex.new @prev_time = nil @colored_namespaces = {} end
Public Instance Methods
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.
@param message [String] @param namespace [String, Symbol] (default: nil) @return [NilClass]
# 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
Private Instance Methods
Colorize a string
by adding ANSI escape codes for a specific color
See {Lug::Colors}
@param string [String] @param color [String] @return [String] colored string
# File lib/lug/logger.rb, line 276 def colorize(string, color) "\e[#{color}m#{string}\e[0m" end
Colorize a namespace
string
Tries to use a different color than the one used for the previous namespace used.
@param namespace [String, Symbol] @return [String] colored namespace string
# File lib/lug/logger.rb, line 263 def colorize_namespace(namespace) @colored_namespaces[namespace] ||= colorize(namespace, NS_COLORS[@colored_namespaces.size % NS_COLORS.size]) end
Calculates elapsed time from previous call to log
up to now
Returns a string that represents elapsed time rounded to minutes, seconds or milliseconds.
@param now [Time] @return [String]
# File lib/lug/logger.rb, line 288 def elapsed_text(now) secs = now - (@prev_time || now) if secs >= 60 "+#{(secs / 60).to_i}m" elsif secs >= 1 "+#{secs.to_i}s" else "+#{(secs * 1000).to_i}ms" end end