Skip to content

Instantly share code, notes, and snippets.

@acook
Last active December 11, 2015 06:39
Show Gist options
  • Save acook/4561129 to your computer and use it in GitHub Desktop.
Save acook/4561129 to your computer and use it in GitHub Desktop.
Log reader can tail logs and will restart logs that have been rotated. Subclass and replace the `process` method!
class LogReader
def self.open filename
new File.open filename, 'r'
end
def initialize file
raise ArgumentError, 'File required!' unless File === file
@file = file
end
attr :file
def tail
loop do
wait
line = file.gets
process line
end
ensure
file.close
end
protected
def process line
puts line
end
def wait
until readable? do
sleep 1
end
end
def readable?
raise EOFError, 'File deleted or changed.' if altered?
get && unget && true
rescue EOFError
reopen!
end
def get
file.getbyte
end
def unget
file.pos = file.pos - 1
end
def reopen!
return nil unless exists?
save_restore_pos do
file.reopen file.path, 'r'
end
end
def save_restore_pos active = same?
cursor = file.pos if active
yield
file.pos = cursor if active
file
end
def altered?
!(exists? && same?)
end
def exists?
File.exists? file.path
end
def same?
File.stat(file.path).ino == file.stat.ino
end
end
log = LogReader.open '~test'
log.tail
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment