Class: LogClient::Tail

Inherits:
Object show all
Defined in:
lib/nfagent/tail.rb

Defined Under Namespace

Classes: BufferError

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename) ⇒ Tail

Returns a new instance of Tail.



26
27
28
29
30
31
# File 'lib/nfagent/tail.rb', line 26

def initialize(filename)
  @buffer = ""
  @filename = filename
  reset_buffer_size
  seek_and_setup
end

Class Method Details

.tail(filename) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/nfagent/tail.rb', line 12

def self.tail(filename)
  loop do
    Tail.new(filename).run do |line|
      unless line.nil? || line.empty?
        if block_given?
          yield line
        else
          puts line
        end
      end
    end
  end
end

Instance Method Details

#runObject

The real work Start at next start. Read until we get a new line and yield the line If we don’t get a new line then just ignore and try again until we do



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/nfagent/tail.rb', line 36

def run
  begin
    yield @first_line if block_given?
    while (size = File::Stat.new(@filename).size) >= @next_start
      size = @file.stat.size
      reset_buffer_size
      begin
        line = ""
        @file.seek(@next_start, File::SEEK_SET)
        @file.read(@buf_size, @buffer)
        buffer_start = @next_start
        found_new_line = false
        0.upto(@buffer.size - 1) do |index|
          line << @buffer[index]
          if @buffer[index].chr == "\n"
            yield(line) if block_given?
            line = ""
            found_new_line = true
            @next_start = buffer_start + index + 1
          end
        end
        unless found_new_line || @buffer.empty?
          raise BufferError
        end
      rescue BufferError
        increment_buffer_size
        retry
      end
	  sleep 0.01
    end
  rescue Errno::ENOENT
    # Wait until the file is recreated
    while !File.exists?(@filename)
      sleep 0.05
    end
  end
end