LoggingHandler.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from __future__ import annotations
  2. import logging
  3. import tqdm
  4. class LoggingHandler(logging.Handler):
  5. def __init__(self, level=logging.NOTSET) -> None:
  6. super().__init__(level)
  7. def emit(self, record) -> None:
  8. try:
  9. msg = self.format(record)
  10. tqdm.tqdm.write(msg)
  11. self.flush()
  12. except (KeyboardInterrupt, SystemExit):
  13. raise
  14. except Exception:
  15. self.handleError(record)
  16. def install_logger(given_logger, level=logging.WARNING, fmt="%(levelname)s:%(name)s:%(message)s") -> None:
  17. """Configures the given logger; format, logging level, style, etc"""
  18. import coloredlogs
  19. def add_notice_log_level():
  20. """Creates a new 'notice' logging level"""
  21. # inspired by:
  22. # https://stackoverflow.com/questions/2183233/how-to-add-a-custom-loglevel-to-pythons-logging-facility
  23. NOTICE_LEVEL_NUM = 25
  24. logging.addLevelName(NOTICE_LEVEL_NUM, "NOTICE")
  25. def notice(self, message, *args, **kws):
  26. if self.isEnabledFor(NOTICE_LEVEL_NUM):
  27. self._log(NOTICE_LEVEL_NUM, message, args, **kws)
  28. logging.Logger.notice = notice
  29. # Add an extra logging level above INFO and below WARNING
  30. add_notice_log_level()
  31. # More style info at:
  32. # https://coloredlogs.readthedocs.io/en/latest/api.html
  33. field_styles = coloredlogs.DEFAULT_FIELD_STYLES.copy()
  34. field_styles["asctime"] = {}
  35. level_styles = coloredlogs.DEFAULT_LEVEL_STYLES.copy()
  36. level_styles["debug"] = {"color": "white", "faint": True}
  37. level_styles["notice"] = {"color": "cyan", "bold": True}
  38. coloredlogs.install(
  39. logger=given_logger,
  40. level=level,
  41. use_chroot=False,
  42. fmt=fmt,
  43. level_styles=level_styles,
  44. field_styles=field_styles,
  45. )