blob: cf3ee136e0ad405c7131fdb0e69429a45ef2ad12 [file] [log] [blame]
Jeremy Hylton6fa82a32002-06-04 20:00:26 +00001"""A simple log mechanism styled after PEP 282."""
2
Martin v. Löwis5a6601c2004-11-10 22:23:15 +00003# This module should be kept compatible with Python 2.1.
Andrew M. Kuchlingd448f662002-11-19 13:12:28 +00004
Jeremy Hylton6fa82a32002-06-04 20:00:26 +00005# The class here is styled after PEP 282 so that it could later be
6# replaced with a standard Python logging implementation.
7
8DEBUG = 1
9INFO = 2
10WARN = 3
11ERROR = 4
12FATAL = 5
13
Andrew M. Kuchlinge2d12142002-11-04 14:27:43 +000014import sys
15
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000016class 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 print msg % args
Andrew M. Kuchlinge2d12142002-11-04 14:27:43 +000024 sys.stdout.flush()
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000025
26 def log(self, level, msg, *args):
27 self._log(level, msg, args)
28
29 def debug(self, msg, *args):
30 self._log(DEBUG, msg, args)
Tim Peters182b5ac2004-07-18 06:16:08 +000031
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000032 def info(self, msg, *args):
33 self._log(INFO, msg, args)
Tim Peters182b5ac2004-07-18 06:16:08 +000034
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000035 def warn(self, msg, *args):
36 self._log(WARN, msg, args)
Tim Peters182b5ac2004-07-18 06:16:08 +000037
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000038 def error(self, msg, *args):
39 self._log(ERROR, msg, args)
Tim Peters182b5ac2004-07-18 06:16:08 +000040
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000041 def fatal(self, msg, *args):
42 self._log(FATAL, msg, args)
43
44_global_log = Log()
45log = _global_log.log
46debug = _global_log.debug
47info = _global_log.info
48warn = _global_log.warn
49error = _global_log.error
50fatal = _global_log.fatal
51
52def set_threshold(level):
Fred Drakeedcac8f2004-08-03 18:53:07 +000053 # return the old threshold for use from tests
54 old = _global_log.threshold
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000055 _global_log.threshold = level
Fred Drakeedcac8f2004-08-03 18:53:07 +000056 return old
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000057
58def set_verbosity(v):
Guido van Rossuma85dbeb2003-02-20 02:09:30 +000059 if v <= 0:
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000060 set_threshold(WARN)
Guido van Rossuma85dbeb2003-02-20 02:09:30 +000061 elif v == 1:
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000062 set_threshold(INFO)
Guido van Rossuma85dbeb2003-02-20 02:09:30 +000063 elif v >= 2:
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000064 set_threshold(DEBUG)