2 # Copyright (C) 2010, 2012 Google Inc. All rights reserved.
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are
8 # * Redistributions of source code must retain the above copyright
9 # notice, this list of conditions and the following disclaimer.
10 # * Redistributions in binary form must reproduce the above
11 # copyright notice, this list of conditions and the following disclaimer
12 # in the documentation and/or other materials provided with the
14 # * Neither the name of Google Inc. nor the names of its
15 # contributors may be used to endorse or promote products derived from
16 # this software without specific prior written permission.
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 LOG_HANDLER_NAME = 'MeteredStreamLogHandler'
39 class MeteredStream(object):
41 This class implements a stream wrapper that has 'meters' as well as
42 regular output. A 'meter' is a single line of text that can be erased
43 and rewritten repeatedly, without producing multiple lines of output. It
44 can be used to produce effects like progress bars.
50 return '\b' * num_chars + ' ' * num_chars + '\b' * num_chars
53 def _ensure_newline(txt):
54 return txt if txt.endswith('\n') else txt + '\n'
56 def __init__(self, stream=None, verbose=False, logger=None, time_fn=None, pid=None):
57 self._stream = stream or sys.stderr
58 self._verbose = verbose
59 self._time_fn = time_fn or time.time
60 self._pid = pid or os.getpid()
62 self._isatty = self._stream.isatty()
63 self._erasing = self._isatty and not verbose
64 self._last_partial_line = ''
65 self._last_write_time = 0.0
66 self._throttle_delay_in_secs = 0.066 if self._erasing else 10.0
69 self._log_handler = None
71 log_level = logging.DEBUG if verbose else logging.INFO
72 self._log_handler = _LogHandler(self)
73 self._log_handler.setLevel(log_level)
74 self._logger.addHandler(self._log_handler)
81 self._logger.removeHandler(self._log_handler)
82 self._log_handler = None
84 def write_throttled_update(self, txt):
86 if now - self._last_write_time >= self._throttle_delay_in_secs:
87 self.write_update(txt, now)
89 def write_update(self, txt, now=None):
92 self._last_partial_line = txt[txt.rfind('\n') + 1:]
94 def write(self, txt, now=None):
95 now = now or self._time_fn()
96 self._last_write_time = now
97 if self._last_partial_line:
98 self._erase_last_partial_line()
100 now_tuple = time.localtime(now)
101 msg = '%02d:%02d:%02d.%03d %d %s' % (now_tuple.tm_hour, now_tuple.tm_min, now_tuple.tm_sec, int((now * 1000) % 1000), self._pid, self._ensure_newline(txt))
105 msg = self._ensure_newline(txt)
107 self._stream.write(msg)
109 def writeln(self, txt, now=None):
110 self.write(self._ensure_newline(txt), now)
112 def _erase_last_partial_line(self):
113 num_chars = len(self._last_partial_line)
114 self._stream.write(self._erasure(self._last_partial_line))
115 self._last_partial_line = ''
118 class _LogHandler(logging.Handler):
119 def __init__(self, meter):
120 logging.Handler.__init__(self)
122 self.name = LOG_HANDLER_NAME
124 def emit(self, record):
125 self._meter.writeln(record.msg, record.created)