log_util.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import logging
  2. import sys
  3. from logging.handlers import TimedRotatingFileHandler, SocketHandler
  4. from pathlib import Path
  5. from apps.config import settings
  6. class Log:
  7. ''''''
  8. def __init__(self):
  9. self.available_handlers: list = LogHandlers().get_handlers()
  10. def get_logger(self, logger_name: str):
  11. """
  12. :param logger_name:
  13. :return:
  14. """
  15. logger = logging.getLogger(logger_name)
  16. logger.setLevel(logging.DEBUG)
  17. if logger.hasHandlers():
  18. logger.handlers.clear()
  19. for handler in self.available_handlers:
  20. logger.addHandler(handler)
  21. logger.propagate = False
  22. return logger
  23. class LogHandlers:
  24. def __init__(self):
  25. self.formatter = logging.Formatter("%(asctime)s - %(thread)d - %(name)s - %(levelname)s - %(message)s")
  26. self.log_filename = Path().joinpath(
  27. settings.APP_CONFIG.LOGS_DIR, "fastapi.log")
  28. self.rotation = "midnight"
  29. def get_console_handler(self):
  30. """
  31. :return:
  32. """
  33. console_handler = logging.StreamHandler(sys.stdout.flush())
  34. console_handler.setFormatter(self.formatter)
  35. return console_handler
  36. def get_file_handler(self):
  37. """
  38. :return:
  39. """
  40. file_handler = TimedRotatingFileHandler(
  41. self.log_filename, when=self.rotation)
  42. file_handler.setFormatter(self.formatter)
  43. return file_handler
  44. def get_socket_handler(self):
  45. socket_handler = SocketHandler('127.0.0.1', 19996) # default listening address
  46. return socket_handler
  47. def get_handlers(self):
  48. return [self.get_console_handler(), self.get_file_handler(), self.get_socket_handler()]