import logging
from logging.handlers import RotatingFileHandler
import os

# 获取当前文件的绝对路径
abs_path = os.path.abspath(__file__)
# 获取文件所在目录
directory = os.path.dirname(abs_path)

class LogUtil:
    _instance = None  # 私有类变量，用于存储唯一实例

    def __new__(cls):
        # 如果_instance为None，则创建一个新的实例
        if cls._instance is None:
            cls._instance = super(LogUtil, cls).__new__(cls)
            # 配置logging
            logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            # 创建logger对象
            cls._instance.logger = logging.getLogger('example_logger')
            # 创建一个FileHandler来输出所有级别的日志到指定文件
            log_file = r'{}/example.log'.format(directory)
            file_handler = logging.FileHandler(log_file)
            file_handler.setLevel(logging.DEBUG)
            file_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
            cls._instance.logger.addHandler(file_handler)
        return cls._instance

    def getLogger(self):
        return self.logger
