blob: 97319a07aa861c61043e045ed38759614208e336 [file] [log] [blame]
Jeremy Hylton6fa82a32002-06-04 20:00:26 +00001"""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
Andrew M. Kuchlinge2d12142002-11-04 14:27:43 +000012import sys
13
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000014class Log:
15
16 def __init__(self, threshold=WARN):
17 self.threshold = threshold
18
19 def _log(self, level, msg, args):
20 if level >= self.threshold:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000021 if not args:
22 # msg may contain a '%'. If args is empty,
23 # don't even try to string-format
Guido van Rossumbe19ed72007-02-09 05:37:30 +000024 print(msg)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000025 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000026 print(msg % args)
Andrew M. Kuchlinge2d12142002-11-04 14:27:43 +000027 sys.stdout.flush()
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000028
29 def log(self, level, msg, *args):
30 self._log(level, msg, args)
31
32 def debug(self, msg, *args):
33 self._log(DEBUG, msg, args)
Tim Peters182b5ac2004-07-18 06:16:08 +000034
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000035 def info(self, msg, *args):
36 self._log(INFO, msg, args)
Tim Peters182b5ac2004-07-18 06:16:08 +000037
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000038 def warn(self, msg, *args):
39 self._log(WARN, msg, args)
Tim Peters182b5ac2004-07-18 06:16:08 +000040
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000041 def error(self, msg, *args):
42 self._log(ERROR, msg, args)
Tim Peters182b5ac2004-07-18 06:16:08 +000043
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000044 def fatal(self, msg, *args):
45 self._log(FATAL, msg, args)
46
47_global_log = Log()
48log = _global_log.log
49debug = _global_log.debug
50info = _global_log.info
51warn = _global_log.warn
52error = _global_log.error
53fatal = _global_log.fatal
54
55def set_threshold(level):
Fred Drakeedcac8f2004-08-03 18:53:07 +000056 # return the old threshold for use from tests
57 old = _global_log.threshold
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000058 _global_log.threshold = level
Fred Drakeedcac8f2004-08-03 18:53:07 +000059 return old
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000060
61def set_verbosity(v):
Guido van Rossuma85dbeb2003-02-20 02:09:30 +000062 if v <= 0:
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000063 set_threshold(WARN)
Guido van Rossuma85dbeb2003-02-20 02:09:30 +000064 elif v == 1:
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000065 set_threshold(INFO)
Guido van Rossuma85dbeb2003-02-20 02:09:30 +000066 elif v >= 2:
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000067 set_threshold(DEBUG)