Class: LogTail

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

Overview

Facilitates reading the most recent additions to a log file.

Note that rotation of log files is not handled.

Example:

>> tail = LogTail.new "/var/log/apache2/access.log"
>> tail.state_store.path_to_file = "/tmp/my-state.txt" # Optional: there is a default path
>> tail.each_new_line {|line| puts line }

Direct Known Subclasses

ApacheLogTail

Defined Under Namespace

Classes: FileStateStore

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path_to_file) ⇒ LogTail

Returns a new instance of LogTail.



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

def initialize path_to_file
  @path_to_file = path_to_file
end

Instance Attribute Details

#state_storeObject

Provides a StateStore object that provides persistent storage of a Hash.



21
22
23
# File 'lib/apache_log_tail.rb', line 21

def state_store
  @state_store ||= FileStateStore.new
end

Instance Method Details

#each_new_line(path_to_file = @path_to_file) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/apache_log_tail.rb', line 38

def each_new_line path_to_file = @path_to_file

  # Recall the cursor ( the location in the log file where we left off
  # reading last time)
  state = state_store.recall
  state[:cursor] ||= 0

  File.open  path_to_file do |stream|
    # Move the file reading "head" to the place where we left off reading
    # last time
    stream.seek  state[:cursor]

    stream.each_line {|line| yield line }

    # Remember where the log file reading cursor is for next time:
    state[:cursor] = stream.tell
    state_store.remember  state
  end
end