12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- import logging
- import sys
- from logging.handlers import TimedRotatingFileHandler, SocketHandler
- from pathlib import Path
- from app.config import settings
- class Log:
- ''''''
- def __init__(self):
- self.available_handlers: list = LogHandlers().get_handlers()
-
- def get_logger(self, logger_name: str):
- """
- :param logger_name:
- :return:
- """
- logger = logging.getLogger(logger_name)
- logger.setLevel(logging.DEBUG)
- if logger.hasHandlers():
- logger.handlers.clear()
- for handler in self.available_handlers:
- logger.addHandler(handler)
- logger.propagate = False
- return logger
- class LogHandlers:
- def __init__(self):
- self.formatter = logging.Formatter("%(asctime)s - %(thread)d - %(name)s - %(levelname)s - %(message)s")
- self.log_filename = Path().joinpath(
- settings.APP_CONFIG.LOGS_DIR, "fastapi.log")
- self.rotation = "midnight"
- def get_console_handler(self):
- """
- :return:
- """
- console_handler = logging.StreamHandler(sys.stdout.flush())
- console_handler.setFormatter(self.formatter)
- return console_handler
- def get_file_handler(self):
- """
- :return:
- """
- file_handler = TimedRotatingFileHandler(
- self.log_filename, when=self.rotation)
- file_handler.setFormatter(self.formatter)
- return file_handler
- def get_socket_handler(self):
- socket_handler = SocketHandler('127.0.0.1', 19996) # default listening address
- return socket_handler
- def get_handlers(self):
- return [self.get_console_handler(), self.get_file_handler(), self.get_socket_handler()]
|