当前位置: 首页 > 后端技术 > Python

Pythonlogging日志模板

时间:2023-03-26 18:47:08 Python

importlogging,time,os#当前路径BASE_PATH=os.path.dirname(os.path.dirname(os.path.realpath(__file__)))#定义日志文件路径#LOG_PATH=os.path.join(BASE_PATH,"log")#ifnotos.path.exists(LOG_PATH):#os.mkdir(LOG_PATH)filename=os.path.basename(__file__).split(".")[0]classLogger():def__init__(self):#self.logname=os.path.join(BASE_PATH,"{}.log".format(time.strftime("%Y-%m-%d")))#日志的名称self.logname=os.path.join(BASE_PATH,"{}.log".format(filename))#日志的名称self.logger=logging.getLogger("log")self.logger.setLevel(logging.DEBUG)self.formater=logging.Formatter('[%(asctime)s][%(filename)s%(lineno)d][%(levelname)s]:%(message)s')self.filelogger=logging.FileHandler(self.logname,mode='a',encoding="UTF-8")self.console=logging.StreamHandler()self.console.setLevel(logging.DEBUG)self.filelogger.setLevel(logging.DEBUG)self.filelogger.setFormatter(自己.formater)self.console.setFormatter(self.formater)self.logger.addHandler(self.filelogger)self.logger.addHandler(self.console)如果__name__=='__main__':logger=Logger().logger记录器。info("---测试开始111---")logger.debug("---测试结束222---")