log.py 1.6 KB

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