class Cabin::Outputs::IO

Wrap IO objects with a reasonable log output.

If the IO is not attached to a tty (io#tty? returns false), then the event will be written in ruby inspect format terminated by a newline:

{ "timestamp" => ..., "message" => message, ... }

If the IO is attached to a TTY, there are # human-friendly in this format:

message { event data }

Additionally, colorized output may be available. If the event has :level, :color, or :bold. Any of the Cabin::Mixins::Logger methods (info, error, etc) will result in colored output. See the LEVELMAP for the mapping of levels to colors.

Constants

CODEMAP

Mapping of color/style names to ANSI control values

LEVELMAP

Map of log levels to colors

Public Class Methods

new(io) click to toggle source
# File lib/cabin/outputs/io.rb, line 43
def initialize(io)
  @io = io
  @lock = Mutex.new
end

Public Instance Methods

<<(event) click to toggle source

Receive an event

# File lib/cabin/outputs/io.rb, line 49
def <<(event)
  @lock.synchronize do
    if !tty?
      @io.puts(event.inspect)
    else
      tty_write(event)
    end
  end
end
tty?() click to toggle source
# File lib/cabin/outputs/io.rb, line 59
def tty?
  @io.tty?
end

Private Instance Methods

tty_write(event) click to toggle source
# File lib/cabin/outputs/io.rb, line 63
def tty_write(event)
  # The io is attached to a tty, so make pretty colors.
  # delete things from the 'data' portion that's not really data.
  data = event.clone
  data.delete(:message)
  data.delete(:timestamp)

  color = data.delete(:color)
  # :bold is expected to be truthy
  bold = data.delete(:bold) ? :bold : nil

  # Make 'error' and other log levels have color
  if color.nil? and data[:level]
    color = LEVELMAP[data[:level]]
  end

  if data.empty?
    message = [event[:message]]
  else
    message = ["#{event[:message]} #{data.inspect}"]
  end
  message.unshift("\e[#{CODEMAP[color.to_sym]}m") if !color.nil?
  message.unshift("\e[#{CODEMAP[bold]}m") if !bold.nil?
  message.push("\e[#{CODEMAP[:normal]}m") if !(bold.nil? and color.nil?)
  @io.puts(message.join(""))
  @io.flush
end