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