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