• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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                    emitter(m)
27    finally:
28        ts_mon.close()
29        ts_mon.flush()
30
31
32def SetupLogging(args):
33    """Sets up logging based on the parsed arguments."""
34    # Set up logging.
35    root = logging.getLogger()
36    if args.output_logfile:
37        handler = handlers.RotatingFileHandler(
38            args.output_logfile, maxBytes=10**6, backupCount=5)
39        root.addHandler(handler)
40    else:
41        root.addHandler(logging.StreamHandler(sys.stdout))
42    root.setLevel(logging.DEBUG)
43