Python log monitoring (pronunciation)
Some friends asked me to help with a log monitoring script some time ago. The requirements are as follows:
- 1. windows Environment
- 2. Sound is triggered when the keyword of the log is matched. The matching keyword is different and the playing sound is different.
- 3. Real-Time Response
So I found a windows tail from the Internet and wrote a small script using python. The Code is as follows:
#! /Usr/bin/env python # encoding: UTF-8 "" MonitorLog. pyUsage: MonitorLog. py... monitor the log file-f log file-h help infopython MonitorLog. py-f C: \ monitor. logCreated by zhoubo on 2011-08-29. "import sysimport osimport getoptimport subprocessimport timeimport codecsimport winsoundABSPATH = OS. path. dirname (OS. path. abspath (_ file _) MONITERCONF = 'moniter_keyword.txt '# utf8 filedef main (): try: opts, args = getopt. getopt (sys. argv [1:], 'hf: ') Doesn't 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 # command line tuples cmd = ('tail', '-F ', path) print ''. join (cmd) output = subprocess. popen (cmd, stdout = subprocess. PIPE) keywordMap ={}# load monitoring keyword information 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. The processing code after the output is obtained. 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 0if _ name _ = '_ main _': sys. exit (main ())
The moniter_keyword.txt format is keyword: sound.wav. The example file is as follows:
192.168.8.84:1.wavsha1:3.wavdownload:2.wav