my_logger.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import os
  2. import logging
  3. import sys
  4. import __main__
  5. from typing import List, Dict
  6. FORMAT = "%(asctime)-14s %(levelname)-8s %(module)s:%(lineno)s %(message)s"
  7. class ListLogger(logging.Handler): # Inherit from logging.Handler
  8. def __init__(self):
  9. logging.Handler.__init__(self)
  10. self.running = False
  11. self.log_lists: Dict[str, List[str]] = {}
  12. def start(self):
  13. self.running = True
  14. self.log_lists.clear()
  15. def stop(self):
  16. self.running = False
  17. self.log_lists.clear()
  18. def emit(self, record):
  19. if self.running:
  20. level_name = record.levelname
  21. if hasattr(record, 'end_user') and record.end_user:
  22. level_name = 'END_USER_' + level_name
  23. self.log_lists.setdefault(level_name, []).append(record.msg)
  24. def end_user_warning(msg):
  25. logging.warning(msg, extra={'end_user': True})
  26. def end_user_info(msg):
  27. logging.info(msg, extra={'end_user': True})
  28. list_handler = ListLogger()
  29. logging = logging
  30. try:
  31. logfile = 'logs/' + os.path.normpath(__main__.__file__).replace(os.path.abspath('.'), '') + '.log'
  32. except AttributeError:
  33. print('WARNING: unable to set log file path.')
  34. else:
  35. try:
  36. os.makedirs(os.path.dirname(logfile), exist_ok=True)
  37. logging.basicConfig(filename=logfile, filemode="a+", format=FORMAT)
  38. except OSError:
  39. print('WARNING: unable to set log file path.')
  40. stdout_logger = logging.StreamHandler(sys.stdout)
  41. stdout_logger.setFormatter(logging.Formatter(FORMAT))
  42. logging.getLogger().addHandler(stdout_logger)
  43. logging.getLogger().addHandler(list_handler)
  44. logging.getLogger().setLevel(logging.INFO)