Python 监控日志的简单示例

前端之家收集整理的这篇文章主要介绍了Python 监控日志的简单示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
对python这个高级语言感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧!

一个简易的日志监控的脚本,功能如下:

1.windows环境

2.当匹配日志关键字时会发出声音,匹配的关键字不同,播放的声音不同

3.能做到实时响应

注意:是在win环境下哦

 

直接上代码


# @param Python监控日志程序
# @author 编程之家 jb51.cc|www.jb51.cc 

#!/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 sys
import os
import getopt
import subprocess
import time
import codecs
import 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())

# End www.jb51.cc
原文链接:https://www.f2er.com/python/526978.html

猜你在找的Python相关文章