實時監控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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM