筆者工作中需要監控線上機器的日誌,然後讀取每一行日誌進行處理。
在linux機器上,使用如下的指令可以實時監控日誌的產生。
tail -f test.log
使用tail命令的-f選項可以方便地查閱正在改變的日誌檔案,會把所監控檔案最尾部的內容顯示在螢幕上,並且不斷重新整理。
而筆者需要實時得獲取新增的日誌,並且進行分析處理。
直接上python**。
#log的路徑
test_log = "
/home/work/test/test.log
"def
main(self):
test_log.seek(0,2)#
從檔案末尾開始讀
while
true:
where = test_log.tell()#
獲取檔案末尾的位置
log_line = test_log.readline().strip()#
讀取一行
ifnot
log_line:
test_log.seek(where)
else
:
log_line
if__name__ == "
__main__":
main()
但筆者也發現乙個問題,由於所監控的檔案每秒會新增6k多行的日誌,所以有時會出現列印出的日誌行不完整的現象。
目前看到,使用如下的方法,可以解決這個問題。
#log的路徑
test_log = "
/home/work/test/test.log
"def
main(self):
test_log.seek(0,2)#
從檔案末尾開始讀
log_line =test_log.readline()
while
true:
if log_line.endswith("\n"
):
#可以加上處理邏輯
log_line
log_line =test_log.readline()
else
: log_line +=test_log.readline()
if__name__ == "
__main__":
main()
python實現功能 python實現wc功能
拿到題目後,發現這個作業需要開啟檔案,使用正規表示式匹配,接受命令行引數等操作,於是就有搜尋引擎查詢了許多有關這方面的內容.整體設計思路是使用命令列引數進行for迴圈,再使用if elif else進行匹配,每個命令列引數的實現做成乙個函式 實現了 a c l w 的功能 l 功能 只需要開啟檔案,...
seek實現linux的tail f 監視功能
1 監視filename檔案的尾部內容 預設10行,相當於增加引數 n 10 重新整理顯示在螢幕上。退出,按下ctrl c。2 3相當於乙個死迴圈 4 5import time 6 with open test.txt rb as f 7 f.seek 0,2 游標移到檔案最後 8while tru...
python實現支付功能
支付寶開發者公鑰 支付寶生成 alipay public key os.path.join base dir,utils paycenter alipay certs alipay public key alipay public key obj pub openssl.crypto.load pu...