]>
Commit | Line | Data |
---|---|---|
4710c53d | 1 | """A simple log mechanism styled after PEP 282."""\r |
2 | \r | |
3 | # The class here is styled after PEP 282 so that it could later be\r | |
4 | # replaced with a standard Python logging implementation.\r | |
5 | \r | |
6 | DEBUG = 1\r | |
7 | INFO = 2\r | |
8 | WARN = 3\r | |
9 | ERROR = 4\r | |
10 | FATAL = 5\r | |
11 | \r | |
12 | import sys\r | |
13 | \r | |
14 | class Log:\r | |
15 | \r | |
16 | def __init__(self, threshold=WARN):\r | |
17 | self.threshold = threshold\r | |
18 | \r | |
19 | def _log(self, level, msg, args):\r | |
20 | if level not in (DEBUG, INFO, WARN, ERROR, FATAL):\r | |
21 | raise ValueError('%s wrong log level' % str(level))\r | |
22 | \r | |
23 | if level >= self.threshold:\r | |
24 | if args:\r | |
25 | msg = msg % args\r | |
26 | if level in (WARN, ERROR, FATAL):\r | |
27 | stream = sys.stderr\r | |
28 | else:\r | |
29 | stream = sys.stdout\r | |
30 | stream.write('%s\n' % msg)\r | |
31 | stream.flush()\r | |
32 | \r | |
33 | def log(self, level, msg, *args):\r | |
34 | self._log(level, msg, args)\r | |
35 | \r | |
36 | def debug(self, msg, *args):\r | |
37 | self._log(DEBUG, msg, args)\r | |
38 | \r | |
39 | def info(self, msg, *args):\r | |
40 | self._log(INFO, msg, args)\r | |
41 | \r | |
42 | def warn(self, msg, *args):\r | |
43 | self._log(WARN, msg, args)\r | |
44 | \r | |
45 | def error(self, msg, *args):\r | |
46 | self._log(ERROR, msg, args)\r | |
47 | \r | |
48 | def fatal(self, msg, *args):\r | |
49 | self._log(FATAL, msg, args)\r | |
50 | \r | |
51 | _global_log = Log()\r | |
52 | log = _global_log.log\r | |
53 | debug = _global_log.debug\r | |
54 | info = _global_log.info\r | |
55 | warn = _global_log.warn\r | |
56 | error = _global_log.error\r | |
57 | fatal = _global_log.fatal\r | |
58 | \r | |
59 | def set_threshold(level):\r | |
60 | # return the old threshold for use from tests\r | |
61 | old = _global_log.threshold\r | |
62 | _global_log.threshold = level\r | |
63 | return old\r | |
64 | \r | |
65 | def set_verbosity(v):\r | |
66 | if v <= 0:\r | |
67 | set_threshold(WARN)\r | |
68 | elif v == 1:\r | |
69 | set_threshold(INFO)\r | |
70 | elif v >= 2:\r | |
71 | set_threshold(DEBUG)\r |