1 # Copyright 2013 The Chromium Authors. All rights reserved. 2 # Use of this source code is governed by a BSD-style license that can be 3 # found in the LICENSE file. 4 5 from __future__ import print_function 6 7 import logging 8 import os 9 import sys 10 11 12 def CaptureLogging(f): 13 '''Call the function |f|, capturing any logging output generated. |f| must 14 take no arguments. Returns a list of LogRecords that were emitted. 15 ''' 16 output = [] 17 class Capture(object): 18 def filter(self, record): 19 output.append(record) 20 21 cf = Capture() 22 logging.getLogger('').addFilter(cf) 23 f() 24 logging.getLogger('').removeFilter(cf) 25 26 return output 27 28 29 def EnableLogging(name): 30 '''Returns the output of the log with |name| to stdout. 31 ''' 32 33 return _ReplaceLogging(name, lambda message, *args: print(message % args)) 34 35 36 def DisableLogging(name): 37 '''Disables the log with |name| for the duration of the decorated function. 38 ''' 39 return _ReplaceLogging(name, lambda _, *args: None) 40 41 42 def _ReplaceLogging(name, replacement): 43 def decorator(fn): 44 def impl(*args, **optargs): 45 saved = getattr(logging, name) 46 setattr(logging, name, replacement) 47 try: 48 return fn(*args, **optargs) 49 finally: 50 setattr(logging, name, saved) 51 return impl 52 return decorator 53 54 55 def ChromiumPath(*path): 56 return os.path.join( 57 sys.path[0], '..', '..', '..', '..', '..', *path) 58 59 60 def ReadFile(*path, **read_args): 61 with open(ChromiumPath(*path), **read_args) as f: 62 return f.read() 63