Class: Llv::Tailer

Inherits:
Object
  • Object
show all
Defined in:
lib/llv/tailer.rb

Overview

Follows a log file from EOF (or from start). Emits each new line to the supplied block on a background thread. Handles truncation/rotation by re-opening the file when its size shrinks or its inode changes.

Instance Method Summary collapse

Constructor Details

#initialize(path, from_start: false) ⇒ Tailer

Returns a new instance of Tailer.



10
11
12
13
14
15
16
17
# File 'lib/llv/tailer.rb', line 10

def initialize(path, from_start: false)
  @path = File.expand_path(path)
  @from_start = from_start
  @buffer = +""
  @position = 0
  @inode = nil
  @stop = false
end

Instance Method Details

#each_line(&block) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/llv/tailer.rb', line 19

def each_line(&block)
  @on_line = block
  open_initial
  emit_existing if @from_start
  @position = File.size(@path)
  @inode = File.stat(@path).ino

  @listener = Listen.to(File.dirname(@path), only: Regexp.new("\\A#{Regexp.escape(File.basename(@path))}\\z")) do
    check_for_changes
  end
  @listener.start

  # Also poll occasionally as a fallback (some editors swap files in ways listen misses).
  @poll = Thread.new do
    until @stop
      sleep 0.5
      check_for_changes
    end
  end

  self
end

#stopObject



42
43
44
45
46
# File 'lib/llv/tailer.rb', line 42

def stop
  @stop = true
  @listener&.stop
  @poll&.join(1)
end