Style fixes for release modules.
[Melange.git] / scripts / release / log.py
blob06f6235b8b40285069d5fbfdaaab527abdb51f42
1 # Copyright 2009 the Melange authors.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 """Logging facilities.
17 The public interface is basically an initialization function for the
18 underlying Python logging module. Logging always goes to the console,
19 and can optionally be configured to write to a transcript file, which
20 will store exactly what appears on screen (minus colors).
21 """
23 __authors__ = [
24 # alphabetical order by last name, please
25 '"David Anderson" <dave@natulte.net>',
29 import logging
30 import sys
32 import util
35 # A logging level that is even lower than DEBUG. We use this level to
36 # log to file only, when we need to replay something output by
37 # bypassing the logging system.
38 _TERMINAL_ECHO = 5
41 # Pull in the functions from the logging module, for ease of use
42 debug = logging.debug
43 info = logging.info
44 error = logging.error
45 raw = debug # Used for logging raw output like subprocess stdout data.
48 # Save the actual out/err streams before init() replaces them. Users
49 # of the logging system can use these files if they need to bypass the
50 # logging system for some reason.
51 stdout = sys.stdout
52 stderr = sys.stderr
55 class _ColorizingFormatter(logging.Formatter):
56 """A logging formatter that colorizes based on log levels."""
58 def format(self, record):
59 msg = logging.Formatter.format(self, record)
61 if record.levelno >= logging.WARNING:
62 return util.colorize(msg, util.RED, bold=True)
63 elif record.levelno == logging.INFO:
64 return util.colorize(msg, util.GREEN)
65 else:
66 return msg
69 class _DecolorizingFormatter(logging.Formatter):
70 """A logging formatter that strips color."""
72 def format(self, record):
73 return util.decolorize(logging.Formatter.format(self, record))
76 class FileLikeLogger(object):
77 """A file-like object that logs anything written to it."""
79 def __init__(self):
80 self._buffer = []
82 def _getBuffer(self):
83 data, self._buffer = ''.join(self._buffer), []
84 return data
86 def close(self):
87 self.flush()
89 def flush(self):
90 raw(self._getBuffer())
92 def write(self, str):
93 lines = str.split('\n')
94 self.writelines(lines[0:-1])
95 self._buffer.append(lines[-1])
97 def writelines(self, lines):
98 if not lines:
99 return
100 lines[0] = self._getBuffer() + lines[0]
101 for line in lines:
102 raw(line)
105 def init(logfile=None):
106 """Initialize the logging subsystem.
108 Args:
109 logfile: The filename for the transcript file, if any.
112 root = logging.getLogger('')
113 root.setLevel(_TERMINAL_ECHO)
115 console = logging.StreamHandler()
116 console.setLevel(logging.DEBUG)
117 console.setFormatter(_ColorizingFormatter())
118 root.addHandler(console)
120 if logfile:
121 transcript = logging.FileHandler(logfile, 'w')
122 transcript.setLevel(_TERMINAL_ECHO)
123 transcript.setFormatter(_DecolorizingFormatter())
124 root.addHandler(transcript)
126 # Redirect sys.stdout and sys.stderr to logging streams. This will
127 # force everything that is output in this process, even through
128 # 'print', to go to both the console and the transcript (if active).
129 sys.stdout = FileLikeLogger()
130 sys.stderr = FileLikeLogger()
133 def terminal_echo(text, *args, **kwargs):
134 """Echo a message written manually to the terminal.
136 This function should be used when you want to echo into the logging
137 system something that you manually wrote to the real
138 stdout/stderr.
140 For example, when asking the user for input, you would output the
141 raw prompt to the terminal manually, read the user's response, and
142 then echo both the prompt and the answer back into the logging
143 system for recording.
145 logging.log(_TERMINAL_ECHO, text, *args, **kwargs)