TailFollow enables a user to read new data as it is appended to a file in a manner similar to a 'tail -f' command. As a file is moved or rotated (perhaps as part of a log rotation mechanism), TailFollow can continue to read from the file as it moves until a new file is created in the original location.
The simple (non-tracking mode) usage of TailFollow is as follows:
tail = TailFollow("/var/log/syslog")
for line in tail:
print line,
tail.close()
When tracking changes to a file, usage is as follows:
while 1:
tail = TailFollow("/var/log/syslog", track=1)
for line in tail:
print line,
time.sleep(1)
tail.close()
It is important to insert a delay to avoid a busy loop in which the TailFollow tries to determine if the file has moved. Failure to do so will result in excessive CPU consumption when the end of file occurs.
- class TailFollow(object):
Tail a file and follow as additional data is appended. TailFollow can be used to monitor log files. It can also track when a the file has been moved (perhaps by a log rotation script). In this case, TailFollow will automatically close the old file, and re-open the new file.
- __init__(filename, track=1):
- Constructor that specifies the file to be tailed. An optional keyword argument specifies whether or not the file should be tracked.
- __iter__():
- Returns an iterator that can be used to iterate over the lines of the file as they are appended. TailFollow implements the iterator contract, as a result, self is returned to the caller.
- next():
- Returns the next line from the file being tailed. This method is part of the iterator contract. StopIteration is thrown when there an EOF has been reached.
- close():
- Closes the current file.