blob: e4959d649215a09cf52f58a753c4c601c5a8e4d5 [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:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000023 if not args:
24 # msg may contain a '%'. If args is empty,
25 # don't even try to string-format
Guido van Rossumbe19ed72007-02-09 05:37:30 +000026 print(msg)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000027 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000028 print(msg % args)
Andrew M. Kuchlinge2d12142002-11-04 14:27:43 +000029 sys.stdout.flush()
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000030
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)
Tim Peters182b5ac2004-07-18 06:16:08 +000036
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000037 def info(self, msg, *args):
38 self._log(INFO, msg, args)
Tim Peters182b5ac2004-07-18 06:16:08 +000039
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000040 def warn(self, msg, *args):
41 self._log(WARN, msg, args)
Tim Peters182b5ac2004-07-18 06:16:08 +000042
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000043 def error(self, msg, *args):
44 self._log(ERROR, msg, args)
Tim Peters182b5ac2004-07-18 06:16:08 +000045
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000046 def fatal(self, msg, *args):
47 self._log(FATAL, msg, args)
48
49_global_log = Log()
50log = _global_log.log
51debug = _global_log.debug
52info = _global_log.info
53warn = _global_log.warn
54error = _global_log.error
55fatal = _global_log.fatal
56
57def set_threshold(level):
Fred Drakeedcac8f2004-08-03 18:53:07 +000058 # return the old threshold for use from tests
59 old = _global_log.threshold
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000060 _global_log.threshold = level
Fred Drakeedcac8f2004-08-03 18:53:07 +000061 return old
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000062
63def set_verbosity(v):
Guido van Rossuma85dbeb2003-02-20 02:09:30 +000064 if v <= 0:
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000065 set_threshold(WARN)
Guido van Rossuma85dbeb2003-02-20 02:09:30 +000066 elif v == 1:
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000067 set_threshold(INFO)
Guido van Rossuma85dbeb2003-02-20 02:09:30 +000068 elif v >= 2:
Jeremy Hylton6fa82a32002-06-04 20:00:26 +000069 set_threshold(DEBUG)