- think shell -
  • HOME
  • BLOG
  • NETWORK TOOLS
    • GeoIP
    • CC Ranges
  • CONTACT
  • Blog
  • 2009
  • August
  • 11
  • Tail -f in python, truncate aware
11 Aug
0

Tail -f in python, truncate aware

Posted by branko | Coding. | Tags: python

While doing a little coding I tried to find some tail -f class in python that will recognize when file that we tailing is been truncated. All I found was some tail -f classes that brakes on file truncate or rotate.

Eventually I came up with this

import time
from os import stat
from os.path import abspath
from stat import ST_SIZE

class LogTail:
    def __init__(self, logfile):
        self.logfile = abspath(logfile)
        self.f = open(self.logfile,"r")
        file_len = stat(self.logfile)[ST_SIZE]
        self.f.seek(file_len)
        self.pos = self.f.tell()
    def _reset(self):
        self.f.close()
        self.f = open(self.logfile, "r")
        self.pos = self.f.tell()
    def tail(self):
        while 1:
            self.pos = self.f.tell()
            line = self.f.readline()
            if not line:
                if stat(self.logfile)[ST_SIZE] < self.pos:
                    self._reset()
                else:
                    time.sleep(1)
                    self.f.seek(self.pos)
            else:
                """print, return or otherwise manipulate
                the tailed line"""
                print line

Maybe it's a too much overhead to check each time for file size, but you get the general idea.

So anyways here's a usage example

tail = LogTail("/var/log/messages")
tail.tail()

This will print out any new line appended to /var/log/messages file. If the file gets truncated or log rotated, class will detect it and will return to the start.

  • Previous entry
  • Next entry

Categories

  • Coding (5)
  • Linux (8)
  • Monitoring (2)
  • Services (1)
  • Tutorials (6)
  • Virtualization (3)

Recent Post

  • IPv4 country code IP ranges database

    23 June 2013
  • Apache monitoring tool ApTop beta released

    12 December 2012
  • Reclaiming InnoDB ibdata unused space.

    04 December 2012
  • Wsgi on cPanel improved

    27 March 2011
  • Django on cpanel with python2.6, virtualenv and mod_wsgi

    14 August 2010

Follow Me

Categories

  • Coding (5)
  • Linux (8)
  • Monitoring (2)
  • Services (1)
  • Tutorials (6)
  • Virtualization (3)

Archives

  • 2008
  • 2009
  • 2010
  • 2011
  • 2012
  • 2013

Recent Posts

  • IPv4 country code IP ranges database 23 June 2013

  • Apache monitoring tool ApTop beta released 12 December 2012

  • Reclaiming InnoDB ibdata unused space. 04 December 2012

© 2015 toic.org All Right Reserved