import logging
import datetime
import os
import copy

from pathlib import Path

project_path = Path(__file__).parent.parent.parent.absolute()
data_path = os.path.join(project_path, 'data')
log_path = os.path.join(project_path, 'logs')


class LoggerClass:
    def __init__(self):
        # 创建日志器对象
        self.format = logging.Formatter(f'[%(filename)s: %(funcName)s:%(lineno)4d][%(asctime)s][%(levelname)-.5s]: '
                                        f'%(message)s',
                                        datefmt='%Y-%m-%d %H:%M:%S')

    def console_handler(self, level):
        # 创建控制台的日志处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(level)

        # 处理器添加输出格式
        console_handler.setFormatter(self.format)

        # 返回控制器
        return console_handler

    def file_handler(self, level, log_file_path):
        # 创建文件的日志处理器
        if os.path.isdir(log_file_path):
            path = os.path.join(log_file_path, 'default_log.txt')
        else:
            path = log_file_path
        file_handler = logging.FileHandler(path, mode="a", encoding="utf-8")
        file_handler.setLevel(level)

        # 处理器添加输出格式
        file_handler.setFormatter(self.format)

        # 返回控制器
        return file_handler

    def get_log(self, level, log_file_path=log_path, name=None):
        if not name or not isinstance(name, str):
            name = 'project_logger'
        logger = logging.getLogger(name=name)
        logger.setLevel(level)
        # 日志器中添加控制台处理器
        logger.addHandler(self.console_handler(level))
        # 日志器中添加文件处理器
        logger.addHandler(self.file_handler(level, log_file_path))

        # 返回日志实例对象
        return logger


if __name__ == '__main__':
    # log = LoggerClass()
    # test_logger = log.get_log(logging.DEBUG)
    # test_logger.debug('debug')
    # test_logger.info('info')
    # test_logger.warning('warning')
    # test_logger.error('error')
    # test_logger.critical('critical')
    pass
