log.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. try:
  24. stream.write('%s\n' % msg)
  25. except UnicodeEncodeError:
  26. # emulate backslashreplace error handler
  27. encoding = stream.encoding
  28. msg = msg.encode(encoding, "backslashreplace").decode(encoding)
  29. stream.write('%s\n' % msg)
  30. stream.flush()
  31. def log(self, level, msg, *args):
  32. self._log(level, msg, args)
  33. def debug(self, msg, *args):
  34. self._log(DEBUG, msg, args)
  35. def info(self, msg, *args):
  36. self._log(INFO, msg, args)
  37. def warn(self, msg, *args):
  38. self._log(WARN, msg, args)
  39. def error(self, msg, *args):
  40. self._log(ERROR, msg, args)
  41. def fatal(self, msg, *args):
  42. self._log(FATAL, msg, args)
  43. _global_log = Log()
  44. log = _global_log.log
  45. debug = _global_log.debug
  46. info = _global_log.info
  47. warn = _global_log.warn
  48. error = _global_log.error
  49. fatal = _global_log.fatal
  50. def set_threshold(level):
  51. # return the old threshold for use from tests
  52. old = _global_log.threshold
  53. _global_log.threshold = level
  54. return old
  55. def set_verbosity(v):
  56. if v <= 0:
  57. set_threshold(WARN)
  58. elif v == 1:
  59. set_threshold(INFO)
  60. elif v >= 2:
  61. set_threshold(DEBUG)