1from __future__ import print_function 2 3import sys 4from logging import handlers 5 6import common 7 8from chromite.lib import cros_logging as logging 9from infra_libs import ts_mon 10 11 12def RunMatchers(stream, matchers): 13 """Parses lines of |stream| using patterns and emitters from |matchers| 14 15 @param stream: A file object to read from. 16 @param matchers: A list of pairs of (matcher, emitter), where matcher is a 17 regex and emitter is a function called when the regex matches. 18 """ 19 # The input might terminate if the log gets rotated. Make sure that Monarch 20 # flushes any pending metrics before quitting. 21 try: 22 for line in iter(stream.readline, ''): 23 for matcher, emitter in matchers: 24 m = matcher.match(line) 25 if m: 26 logging.debug('Emitting %s for input "%s"', 27 emitter.__name__, line.strip()) 28 emitter(m) 29 finally: 30 ts_mon.close() 31 ts_mon.flush() 32 33 34def SetupLogging(args): 35 """Sets up logging based on the parsed arguments.""" 36 # Set up logging. 37 root = logging.getLogger() 38 if args.output_logfile: 39 handler = handlers.RotatingFileHandler( 40 args.output_logfile, maxBytes=10**6, backupCount=5) 41 root.addHandler(handler) 42 else: 43 root.addHandler(logging.StreamHandler(sys.stdout)) 44 root.setLevel(logging.DEBUG) 45