1.变更升级:优化日志自定义输出到文件的level,以及文件夹生成用户自由控制
# coding=utf-8 import logging import time import os import logging.handlers import re def logger(appName,rootstdout=True,handlerList=None): log_fmt= "%(asctime)s --%(name)s-- [%(levelname)s]:\n%(message)s" c_fmt="%(asctime)s --%(name)s-- %(filename)s.%(funcName)s():line %(lineno)d [%(levelname)s]:\n%(message)s" date_format = "%Y-%m-%d %H:%M:%S %a" # 设置控制台输出level logging.basicConfig(level=logging.DEBUG, format=c_fmt, datefmt=date_format, ) levels=[] if isinstance(handlerList,list): if handlerList.__contains__("I") or handlerList.__contains__("Info"): levels.append("Info") if handlerList.__contains__("D") or handlerList.__contains__("Debug"): levels.append("Debug") if handlerList.__contains__("E") or handlerList.__contains__("Error"): levels.append("Error") if handlerList.__contains__("W") or handlerList.__contains__("Warning"): levels.append("Warning") if levels: stamp = "dailylog.log" logsdir=os.path.join(os.getcwd(),"logs") if os.path.exists(logsdir): for p in levels: if os.path.exists(os.path.join(logsdir,p)): pass else: os.mkdir(os.path.join(logsdir,p)) else: os.mkdir(logsdir) for p in levels: os.mkdir(os.path.join(logsdir,p)) f_dict={} for i in levels: filename=os.path.join(logsdir,i,stamp) f_dict[i]=filename logger= logging.getLogger(appName) for k,v in f_dict.items(): handler=logging.handlers.TimedRotatingFileHandler(filename=v,when='MIDNIGHT', interval=1, backupCount=4) handler.suffix = "%Y-%m-%d.log" handler.extMatch = r"^\d{4}-\d{2}-\d{2}.log$" handler.extMatch = re.compile(handler.extMatch) h_fmt=logging.Formatter(log_fmt) handler.setFormatter(h_fmt) if k=="E" or k=="Error": handler.setLevel(logging.ERROR) elif k=="I" or k=="Info": handler.setLevel(logging.INFO) elif k== "W" or k=="Warning": handler.setLevel(logging.WARNING) elif k=="D" or k=="Debug": handler.setLevel(logging.DEBUG) else: raise NameError("check your logLevel Name is corrected or not") logger.addHandler(handler) logger.propagate = rootstdout return logger else: raise TypeError("check handlerList at least one corrected logLevel in:'Error','Info','Warning','Debug'") else: raise NameError("handlerList expected type is list but get type {}".format(type(handlerList).__name__)) if __name__ == "__main__": logger=logger("root",rootstdout=True,handlerList=['E']) time.sleep(0.01) try: assert 1==2 except Exception as e: logger.info("ddd",exc_info=True) logger.debug("bebug test") logger.error("error test") logger.warning("warning test")