#!/usr/bin/python -u """Watch squid's log file for user-specified patterns.""" import re from subprocess import Popen, PIPE import os.path import sys import time __author__ = 'Faried Nawaz' __copyright__ = 'This file is in the public domain.' __version__ = '20090219' # where is the access.log file? LOGFILE = '/var/log/squid/access.log' # sleep for a while between reads (in seconds) SLEEPFOR = 0.5 def usage(msg=None): """Tell the user how to use us.""" progname = os.path.basename(sys.argv[0]) if msg: sys.stderr.write(msg + '\n') sys.stderr.write('''\ usage: %s pattern [pattern ...] examples: %s HIT -- show all lines with "HIT" in them %s \'192.168.1.15.*flickr\' -- show all lines with requests from 192.168.1.15 to flickr %s yahoo gmail hotmail -- show all lines with the words yahoo, gmail, or hotmail in them %s \'text\/plain\' \'text\/javascript\' -- show all lines with requests for plain-text or javascript files note: capitalization matters. ''' % (progname, progname, progname, progname, progname)) sys.exit(1) def watchlogfile(patterns): """Watch a log file for a pattern match.""" pipe = Popen(['tail', '-0f', LOGFILE], stdout=PIPE).stdout while True: time.sleep(SLEEPFOR) line = pipe.readline().strip() if line != '': for pattern in patterns: if pattern.search(line): print line break def main(args): """Main branching logic.""" if len(args) == 0: usage() patterns = [ re.compile(arg) for arg in args ] try: watchlogfile(patterns) except KeyboardInterrupt: sys.exit(0) if __name__ == '__main__': main(sys.argv[1:]) # eof