class ApacheLogTail

(see LogTail)

Will not miss any lines when the log file is rotated between two invocations of each_new_line ( as long as the rotated file has the same name as the original except for a ‘.1` suffix and as long as the file hasn’t been rotated twice between invocations of each_new_line).

Note that this class does not parse Apache log entries, only knows how Apache log files are rotated on Debian. I have enjoyed using the ‘apachelogregex` gem for parsing.

Public Instance Methods

each_new_line() click to toggle source

(see LogTail#each_new_line)

Note: This method must be invoked more frequently than the log file rotation period ( typically 1 week) otherwise an entire file will be missed.

Calls superclass method LogTail#each_new_line
# File lib/apache_log_tail.rb, line 121
def each_new_line
  state = state_store.recall
  first_line_now = first_line_of @path_to_file
  # If the Apache log file has been rotated..
  # The file has been rotated if it has been read ( cursor is remembered) but
  # the first line is not as remembered
  file_has_been_rotated = lambda { state[:cursor] and first_line_now != state[:first_line] }
  if file_has_been_rotated[]
    # Check that the renamed file is as we expect before reading the rest of it:
    renamed_file = @path_to_file + ".1"
    if first_line_of( renamed_file) != state[:first_line]
      raise StandardError.new "Rotated file could not be found"
    end
    # Process the last lines of the rotated file:
    super renamed_file
    # Reset the cursor ready for the new file:
    state[:cursor] = 0
  end
  if first_line_now != state[:first_line]
    state[:first_line] = first_line_now
    state_store.remember state
  end
  # Process the lines that have since been added to the new file:
  super
end

Private Instance Methods

first_line_of(file) click to toggle source
# File lib/apache_log_tail.rb, line 150
def first_line_of file
  File.open  file do |f|
    f.gets
  end
end