實時監控log檔案

lzprgmr發表於2014-07-09

一個程式在執行,並在不斷的寫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

這個可以做為一個不錯的面試題。

相關文章