logger.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import datetime
  2. import logging
  3. import os
  4. import sys
  5. import termcolor
  6. if os.name == "nt": # Windows
  7. import colorama
  8. colorama.init()
  9. from . import __appname__
  10. COLORS = {
  11. "WARNING": "yellow",
  12. "INFO": "white",
  13. "DEBUG": "blue",
  14. "CRITICAL": "red",
  15. "ERROR": "red",
  16. }
  17. class ColoredFormatter(logging.Formatter):
  18. def __init__(self, fmt, use_color=True):
  19. logging.Formatter.__init__(self, fmt)
  20. self.use_color = use_color
  21. def format(self, record):
  22. levelname = record.levelname
  23. if self.use_color and levelname in COLORS:
  24. def colored(text):
  25. return termcolor.colored(
  26. text,
  27. color=COLORS[levelname],
  28. attrs={"bold": True},
  29. )
  30. record.levelname2 = colored("{:<7}".format(record.levelname))
  31. record.message2 = colored(record.msg)
  32. asctime2 = datetime.datetime.fromtimestamp(record.created)
  33. record.asctime2 = termcolor.colored(asctime2, color="green")
  34. record.module2 = termcolor.colored(record.module, color="cyan")
  35. record.funcName2 = termcolor.colored(record.funcName, color="cyan")
  36. record.lineno2 = termcolor.colored(record.lineno, color="cyan")
  37. return logging.Formatter.format(self, record)
  38. logger = logging.getLogger(__appname__)
  39. stream_handler = logging.StreamHandler(sys.stderr)
  40. handler_format = ColoredFormatter(
  41. "[%(levelname2)s] %(module2)s:%(funcName2)s:%(lineno2)s - %(message2)s"
  42. )
  43. stream_handler.setFormatter(handler_format)
  44. logger.addHandler(stream_handler)