python: read file continuously, even after it has been logrotated

前端 未结 3 2062
青春惊慌失措
青春惊慌失措 2021-02-03 13:28

I have a simple python script, where I read logfile continuosly (same as tail -f)

while True:
    line = f.readline()
    if line:
        print lin         


        
3条回答
  •  别跟我提以往
    2021-02-03 14:32

    You can do it by keeping track of where you are in the file and reopening it when you want to read. When the log file rotates, you notice that the file is smaller and since you reopen, you handle any unlinking too.

    import time
    
    cur = 0
    while True:
        try:
            with open('myfile') as f:
                f.seek(0,2)
                if f.tell() < cur:
                    f.seek(0,0)
                else:
                    f.seek(cur,0)
                for line in f:
                    print line.strip()
                cur = f.tell()
        except IOError, e:
            pass
        time.sleep(1)
    

    This example hides errors like file not found because I'm not sure of logrotate details such as small periods of time where the file is not available.

提交回复
热议问题