实时监控log文件

一个进程在运行,并在不断的写log,你需要实时监控log文件的更新(一般是debug时用),怎么办,不断的打开,关闭文件吗? 不用,至少有两个方法,来自两个很常用的命令:

  1. tail -f log.txt, 另外一个进程在写log,而你用tail,就可以实时的打印出新的内容
  2. less log.txt, 然后如果要监控更新,按F,如果要暂停监控,可以CTRL+C, 这样就可以上下翻页查看,要继续监控了再按F即可。这个功能要比tail更强。

可以很容易的模拟一下:

  1. 在一个shell中持续更新文件:
     $ count=1; while true; do echo hello, world $count >> log.txt; count=$(($count+1)); sleep 1s; done
  2. 在另一个shell中tail -f log.txt or less log.txt

 

写一个类似于tail的程序,其实也蛮简单的:

# Notices:
# 1. the 3rd parameter of open() is to disable file buffering
#      so file updated by another process could be picked up correctly
#      but since your focus is newly added tail, enable buffering is ok too
# 2. It is not necessary to fh.tell() to save the position, and then seek()
#     to resume, as if readline() failed, the pointer stay still at the EOF

import sys
import time

filename = sys.argv[1]

with open(filename, 'r', 0) as fh:
    while True:
        line = fh.readline()
        if not line:
            time.sleep(1)
        else:
            print line

这个可以做为一个不错的面试题。

posted @ 2014-07-09 09:16  lzprgmr  阅读(5355)  评论(0编辑  收藏  举报

黄将军