aboutsummaryrefslogtreecommitdiff
path: root/catapult/common/py_utils/py_utils/logging_util.py
blob: 435785116bcf06e5fe554eacb6e2eb6087886545 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Logging util functions.

It would be named logging, but other modules in this directory use the default
logging module, so that would break them.
"""

import contextlib
import logging

@contextlib.contextmanager
def CaptureLogs(file_stream):
  if not file_stream:
    # No file stream given, just don't capture logs.
    yield
    return

  fh = logging.StreamHandler(file_stream)

  logger = logging.getLogger()
  # Try to copy the current log format, if one is set.
  if logger.handlers and hasattr(logger.handlers[0], 'formatter'):
    fh.formatter = logger.handlers[0].formatter
  else:
    fh.setFormatter(logging.Formatter(
        '(%(levelname)s) %(asctime)s %(message)s'))
  logger.addHandler(fh)

  try:
    yield
  finally:
    logger = logging.getLogger()
    logger.removeHandler(fh)