class Towel::LogIO

An IO-like object that logs to Towel. Sits on top of Log. This relationship is inverted compared to most IO class structures, but log lines/entries are the fundamental unit of Towel. This class is merely an adapter to collect logs from IO streams like `$stdout` and `$stderr`.

Public Class Methods

new(log) click to toggle source
# File lib/towel/log_io.rb, line 7
def initialize(log)
  raise ArgumentError, "Log must be specified" unless log
  @log = log
  @buffer = ""
  @write_mutex = Mutex.new
end

Public Instance Methods

<<(obj) click to toggle source
# File lib/towel/log_io.rb, line 60
def <<(obj)
  write(obj)
  self
end
close() click to toggle source
# File lib/towel/log_io.rb, line 92
def close
  @log.close
end
context=(context) click to toggle source
# File lib/towel/log_io.rb, line 14
def context=(context)
  @log.context = context
end
flush() click to toggle source
# File lib/towel/log_io.rb, line 88
def flush
  @log.flush
end
print(*args) click to toggle source
printf(*args) click to toggle source
# File lib/towel/log_io.rb, line 55
def printf(*args)
  write(sprintf(*args))
  nil
end
putc(c) click to toggle source
# File lib/towel/log_io.rb, line 18
def putc(c)
  if c.is_a?(String)
    write(c[0])
  else
    write(c.chr)
  end
  c
end
puts(*args) click to toggle source
# File lib/towel/log_io.rb, line 27
def puts(*args)
  if args.empty?
    write($/)
  else
    args.each do |arg|
      if arg.end_with?($/)
        write(arg)
      else
        write(arg, $/)
      end
    end
  end
  nil
end
write(*args) click to toggle source
# File lib/towel/log_io.rb, line 65
def write(*args)
  @write_mutex.synchronize do
    bytes = 0
    args.each do |arg|
      arg = arg.to_s
      @buffer << arg
      bytes += arg.bytesize
    end

    remaining = ""
    @buffer.each_line do |line|
      if line.end_with?($/)
        @log << line
      else
        remaining = line
      end
    end
    @buffer = remaining

    bytes
  end
end