Python監控日誌程式

來源:互聯網
上載者:User
一個簡易的日誌監控的指令碼,功能如下:1.windows環境2.當匹配日誌關鍵字時會發出聲音,匹配的關鍵字不同,播放的聲音不同3.能做到即時響應

注意:是在win環境下哦

直接上代碼吧

#!/usr/bin/env python# encoding: utf-8   """MonitorLog.py   Usage: MonitorLog.py ...Monitor the log file   -f  log file-h  help info   python MonitorLog.py -f C:\monitor.log   """   import sysimport osimport getoptimport subprocessimport timeimport codecsimport winsound   ABSPATH = os.path.dirname(os.path.abspath(__file__))MONITERCONF = 'moniter_keyword.txt' #utf8 file   def main():    try:        opts, args = getopt.getopt(sys.argv[1:], 'hf:')    except getopt.GetoptError, err:        print str(err)        print __doc__        return 1       path = ''    for k, v in opts:        if k == '-f':            path = v        elif k == '-h':            print __doc__            return 0       if not (path and os.path.exists(path)):        print 'Invalid path: %s' % path         print __doc__        return 2       #命令列元組    cmd = ('tail', '-f', path)    print ' '.join(cmd)    output = subprocess.Popen(cmd, stdout=subprocess.PIPE)       keywordMap = {}    #載入監控的關鍵字資訊    with codecs.open(os.path.join(ABSPATH, MONITERCONF), 'r', 'utf8') as f:        lines = f.readlines()    for line in lines:        line = line.strip()        if not line:            continue        keyword, wav = line.strip().split(':')        keywordMap[keyword] = wav       while True:        line = output.stdout.readline()        #process code,得到輸出資訊後的處理代碼        if not line:            time.sleep(0.01)            continue        line = line.strip().decode('utf8')        print line        for keyword in keywordMap:            if line.find(keyword) > -1:                winsound.PlaySound(keywordMap[keyword],                                    winsound.SND_NODEFAULT)        #time.sleep(0.01)    return 0   if __name__ == '__main__':    sys.exit(main())
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.