實時監控log文件

一個進程在運行,並在不斷的寫log,你須要實時監控log文件的更新(通常是debug時用),怎麼辦,不斷的打開,關閉文件嗎? 不用,至少有兩個方法,來自兩個很經常使用的命令:面試

  1. tail -f log.txt, 另一個進程在寫log,而你用tail,就能夠實時的打印出新的內容
  2. less log.txt, 而後若是要監控更新,按F,若是要暫停監控,能夠CTRL+C, 這樣就能夠上下翻頁查看,要繼續監控了再按F便可。這個功能要比tail更強。

能夠很容易的模擬一下:shell

  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的程序,其實也蠻簡單的:less

# 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

這個能夠作爲一個不錯的面試題。spa

相關文章
相關標籤/搜索