blob: 6f949d517936c6c6ea4fd1ac6cc587be3d6f9fdd [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:
Tarek Ziadéc7cd1382009-03-31 20:48:31 +000021 if args:
22 msg = msg % args
23 if level in (WARN, ERROR, FATAL):
24 stream = sys.stderr
Georg Brandl1c5a59f2006-04-01 07:46:54 +000025 else:
Tarek Ziadéc7cd1382009-03-31 20:48:31 +000026 stream = sys.stdout
27 stream.write('%s\n' % msg)
28 stream.flush()
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000029
30 def log(self, level, msg, *args):
31 self._log(level, msg, args)
32
33 def debug(self, msg, *args):
34 self._log(DEBUG, msg, args)
Tim Peters182b5ac2004-07-18 06:16:08 +000035
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000036 def info(self, msg, *args):
37 self._log(INFO, msg, args)
Tim Peters182b5ac2004-07-18 06:16:08 +000038
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000039 def warn(self, msg, *args):
40 self._log(WARN, msg, args)
Tim Peters182b5ac2004-07-18 06:16:08 +000041
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000042 def error(self, msg, *args):
43 self._log(ERROR, msg, args)
Tim Peters182b5ac2004-07-18 06:16:08 +000044
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000045 def fatal(self, msg, *args):
46 self._log(FATAL, msg, args)
47
48_global_log = Log()
49log = _global_log.log
50debug = _global_log.debug
51info = _global_log.info
52warn = _global_log.warn
53error = _global_log.error
54fatal = _global_log.fatal
55
56def set_threshold(level):
Fred Drakeedcac8f2004-08-03 18:53:07 +000057 # return the old threshold for use from tests
58 old = _global_log.threshold
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000059 _global_log.threshold = level
Fred Drakeedcac8f2004-08-03 18:53:07 +000060 return old
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000061
62def set_verbosity(v):
Guido van Rossuma85dbeb2003-02-20 02:09:30 +000063 if v <= 0:
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000064 set_threshold(WARN)
Guido van Rossuma85dbeb2003-02-20 02:09:30 +000065 elif v == 1:
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000066 set_threshold(INFO)
Guido van Rossuma85dbeb2003-02-20 02:09:30 +000067 elif v >= 2:
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000068 set_threshold(DEBUG)