|
1 # Copyright 2009 the Melange authors. |
|
2 # |
|
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 |
|
6 # |
|
7 # http://www.apache.org/licenses/LICENSE-2.0 |
|
8 # |
|
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. |
|
14 |
|
15 """Logging facilities. |
|
16 |
|
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 """ |
|
22 |
|
23 __authors__ = [ |
|
24 # alphabetical order by last name, please |
|
25 '"David Anderson" <dave@natulte.net>', |
|
26 ] |
|
27 |
|
28 import logging |
|
29 |
|
30 import util |
|
31 |
|
32 |
|
33 class _ColorizingFormatter(logging.Formatter): |
|
34 """A logging formatter that colorizes based on log levels.""" |
|
35 |
|
36 def format(self, record): |
|
37 msg = logging.Formatter.format(self, record) |
|
38 |
|
39 if record.levelno >= logging.WARNING: |
|
40 return util.colorize(msg, util.RED, bold=True) |
|
41 elif record.levelno == logging.INFO: |
|
42 return util.colorize(msg, util.GREEN) |
|
43 else: |
|
44 return msg |
|
45 |
|
46 |
|
47 class _DecolorizingFormatter(logging.Formatter): |
|
48 """A logging formatter that strips color.""" |
|
49 |
|
50 def format(self, record): |
|
51 return util.decolorize(logging.Formatter.format(self, record)) |
|
52 |
|
53 |
|
54 def init(logfile=None): |
|
55 """Initialize the logging subsystem. |
|
56 |
|
57 Args: |
|
58 logfile: The filename for the transcript file, if any. |
|
59 """ |
|
60 |
|
61 root = logging.getLogger('') |
|
62 root.setLevel(logging.DEBUG) |
|
63 |
|
64 console = logging.StreamHandler() |
|
65 console.setLevel(logging.DEBUG) |
|
66 console.setFormatter(_ColorizingFormatter()) |
|
67 root.addHandler(console) |
|
68 |
|
69 if logfile: |
|
70 transcript = logging.FileHandler(logfile, 'w') |
|
71 transcript.setLevel(logging.DEBUG) |
|
72 transcript.setFormatter(_DecolorizingFormatter()) |
|
73 root.addHandler(transcript) |
|
74 |
|
75 |
|
76 debug = logging.debug |
|
77 info = logging.info |
|
78 error = logging.error |