Class: Towel::LogIO

Inherits:
Object
  • Object
show all
Defined in:
lib/towel/log_io.rb

Overview

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`.

Instance Method Summary collapse

Constructor Details

#initialize(log) ⇒ LogIO

Returns a new instance of LogIO.

Raises:

  • (ArgumentError)


7
8
9
10
11
12
# 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

Instance Method Details

#<<(obj) ⇒ Object



60
61
62
63
# File 'lib/towel/log_io.rb', line 60

def <<(obj)
  write(obj)
  self
end

#closeObject



92
93
94
# File 'lib/towel/log_io.rb', line 92

def close
  @log.close
end

#context=(context) ⇒ Object



14
15
16
# File 'lib/towel/log_io.rb', line 14

def context=(context)
  @log.context = context
end

#flushObject



88
89
90
# File 'lib/towel/log_io.rb', line 88

def flush
  @log.flush
end


42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/towel/log_io.rb', line 42

def print(*args)
  if args.empty?
    write($_)
  else
    if $\.nil?
      write(args.join($,))
    else
      write(args.join($,), $\)
    end
  end
  nil
end

#printf(*args) ⇒ Object



55
56
57
58
# File 'lib/towel/log_io.rb', line 55

def printf(*args)
  write(sprintf(*args))
  nil
end

#putc(c) ⇒ Object



18
19
20
21
22
23
24
25
# 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) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 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) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# 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