在自己的项目根路径下新建util包
util包下面新建两个文件
log.py
"""操作日志记录 """ import time from loguru import logger from pathlib import Path from util.pathutil import Pathutil # project_path = Path.cwd().parent pathutil = Pathutil() project_path = pathutil.rootPath log_path = Path(project_path, "log") t = time.strftime("%Y_%m_%d") class Loggings: __instance = None logger.add(f"{log_path}/interface_log_{t}.log", rotation="500MB", encoding="utf-8", enqueue=True, retention="10 days") def __new__(cls, *args, **kwargs): if not cls.__instance: cls.__instance = super(Loggings, cls).__new__(cls, *args, **kwargs) return cls.__instance def info(self, msg): return logger.info(msg) def debug(self, msg): return logger.debug(msg) def warning(self, msg): return logger.warning(msg) def error(self, msg): return logger.error(msg) loggings = Loggings() if __name__ == '__main__': loggings.info("中文test") loggings.debug("中文test") loggings.warning("中文test") loggings.error("中文test") logger.info('If you are using Python {}, prefer {feature} of course!', 3.6, feature='f-strings') n1 = "cool" n2 = [1, 2, 3] logger.info(f'If you are using Python {n1}, prefer {n2} of course!')
pathutil.py
import sys import os class Pathutil(object): """路径处理工具类""" def __init__(self): # 判断调试模式 debug_vars = dict((a, b) for a, b in os.environ.items() if a.find('IPYTHONENABLE') >= 0) # 根据不同场景获取根目录 if len(debug_vars) > 0: """当前为debug运行时""" self.rootPath = sys.path[2] elif getattr(sys, 'frozen', False): """当前为exe运行时""" self.rootPath = os.getcwd() else: """正常执行""" self.rootPath = sys.path[1] # 替换斜杠 self.rootPath = self.rootPath.replace("\", "/") def getPathFromResources(self, fileName): """按照文件名拼接资源文件路径""" filePath = "%s/resources/%s" % (self.rootPath, fileName) return filePath
使用方式:
main.py
from util import log log = log.Loggings() if __name__ == '__main__': log.info("fafa")