log.py 1.9 KB

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