1 | """A simple log mechanism styled after PEP 282."""
|
---|
2 |
|
---|
3 | # This module should be kept compatible with Python 2.1.
|
---|
4 |
|
---|
5 | # The class here is styled after PEP 282 so that it could later be
|
---|
6 | # replaced with a standard Python logging implementation.
|
---|
7 |
|
---|
8 | DEBUG = 1
|
---|
9 | INFO = 2
|
---|
10 | WARN = 3
|
---|
11 | ERROR = 4
|
---|
12 | FATAL = 5
|
---|
13 |
|
---|
14 | import sys
|
---|
15 |
|
---|
16 | class Log:
|
---|
17 |
|
---|
18 | def __init__(self, threshold=WARN):
|
---|
19 | self.threshold = threshold
|
---|
20 |
|
---|
21 | def _log(self, level, msg, args):
|
---|
22 | if level >= self.threshold:
|
---|
23 | if not args:
|
---|
24 | # msg may contain a '%'. If args is empty,
|
---|
25 | # don't even try to string-format
|
---|
26 | print msg
|
---|
27 | else:
|
---|
28 | print msg % args
|
---|
29 | sys.stdout.flush()
|
---|
30 |
|
---|
31 | def log(self, level, msg, *args):
|
---|
32 | self._log(level, msg, args)
|
---|
33 |
|
---|
34 | def debug(self, msg, *args):
|
---|
35 | self._log(DEBUG, msg, args)
|
---|
36 |
|
---|
37 | def info(self, msg, *args):
|
---|
38 | self._log(INFO, msg, args)
|
---|
39 |
|
---|
40 | def warn(self, msg, *args):
|
---|
41 | self._log(WARN, msg, args)
|
---|
42 |
|
---|
43 | def error(self, msg, *args):
|
---|
44 | self._log(ERROR, msg, args)
|
---|
45 |
|
---|
46 | def fatal(self, msg, *args):
|
---|
47 | self._log(FATAL, msg, args)
|
---|
48 |
|
---|
49 | _global_log = Log()
|
---|
50 | log = _global_log.log
|
---|
51 | debug = _global_log.debug
|
---|
52 | info = _global_log.info
|
---|
53 | warn = _global_log.warn
|
---|
54 | error = _global_log.error
|
---|
55 | fatal = _global_log.fatal
|
---|
56 |
|
---|
57 | def set_threshold(level):
|
---|
58 | # return the old threshold for use from tests
|
---|
59 | old = _global_log.threshold
|
---|
60 | _global_log.threshold = level
|
---|
61 | return old
|
---|
62 |
|
---|
63 | def set_verbosity(v):
|
---|
64 | if v <= 0:
|
---|
65 | set_threshold(WARN)
|
---|
66 | elif v == 1:
|
---|
67 | set_threshold(INFO)
|
---|
68 | elif v >= 2:
|
---|
69 | set_threshold(DEBUG)
|
---|