1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| import time from functools import wraps from pathlib import Path import loguru
def singleton_class_decorator(cls): """ 装饰器,单例类的装饰器 """ _instance = {}
@wraps(cls) def wrapper_class(*args, **kwargs): if cls not in _instance: _instance[cls] = cls(*args, **kwargs) return _instance[cls]
return wrapper_class
@singleton_class_decorator class Logger: def __init__(self): self.logger_add()
def get_project_path(self, project_path=None): if project_path is None: project_path = Path.cwd().parent return project_path
def get_log_path(self): project_path = self.get_project_path() creat_time = time.strftime("%Y-%m-%d", time.localtime()) logs_file_path = Path(project_path).joinpath('logs', creat_time) if logs_file_path.exists(): logs_path = logs_file_path else: try: logs_file_path.mkdir(parents=True) except Exception as e: print(f"创建文件报错: {e}") logs_path = logs_file_path project_log_filename = '{}.log'.format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) ) project_log_path = Path(logs_path).joinpath(logs_path, project_log_filename) return project_log_path
def logger_add(self): loguru.logger.add( sink=self.get_log_path(), rotation='00:00', retention='1 day', compression='zip', encoding="utf-8", enqueue=True )
@property def get_logger(self): return loguru.logger
|