可以在其他路径调用该logs方法时,将日志保存在当前日志路径下 import logging import os import inspect LOG_DIR = None class Logs: def getAbsPath(self): current_frame = inspect.currentframe() caller_frame = inspect.getouterframes(current_frame, 2)[1] caller_file = caller_frame.filename caller_dir = os.path.dirname(caller_file) abs_dir = os.path.abspath(caller_dir) os.chdir(abs_dir) return os.getcwd() def log(self, name="logs", level=logging.DEBUG, sh_level=logging.DEBUG, fh_level=logging.DEBUG): global LOG_DIR if LOG_DIR is None: LOG_DIR = self.getAbsPath() log_path = os.path.join(LOG_DIR, 'logs.log') log = logging.getLogger(name) # 2、创建日志收集器的等级 log.setLevel(level=level) # 3、创建日志收集渠道和等级 sh = logging.StreamHandler() sh.setLevel(level=sh_level) log.addHandler(sh) fh = logging.FileHandler(filename=log_path, encoding="utf-8") fh.setLevel(level=fh_level) log.addHandler(fh) # 4、设置日志的输出格式 formats = "%(asctime)s - [%(funcName)s-->line:%(lineno)d] - %(levelname)s:%(message)s" log_format = logging.Formatter(fmt=formats) sh.setFormatter(log_format) fh.setFormatter(log_format) return log if __name__ == '__main__': log = Logs().log() log.info("--------info--------") log.error("--------error--------") log.warning("--------error--------")
python封装绝对路径的logs方法
于 2023-04-06 11:24:40 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)