首先说明错误级别:
常用的几种错误级别:
1,Debug
2,Info
3,Warn
4,Error
5,Fatal
上面这几种错误类型,可以自行百度下,看看具体什么意思,我想大家也应该都了解过了,这里就不做赘述了,下面直接上代码了。
下面粘贴下代码,以便大家使用:
class LogUtils:
def __init__(self):
pass
@classmethod
def writelog(cls,name,message:str,tag:str,level:int=logging.DEBUG):
logger = logging.getLogger()
# streamhandler = logging.StreamHandler()
filename =name+time.strftime('%Y-%m-%d', time.localtime(time.time()))
path="./log"
if not os.path.exists(path):
os.mkdir(path,0o777)
handler = logging.FileHandler(path +"/"+ filename + ".log."+tag)
logger.addHandler(handler)
logger.setLevel(level)
logger.info(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ':' + message)
# 添加下面一句,在记录日志之后移除文件句柄
logger.removeHandler(handler)
@classmethod
def Debug(cls,filename,message):
cls.writelog(filename,message,"debug")
@classmethod
def Info(cls,filename,message):
cls.writelog(filename,message,"info")
@classmethod
def Warn(cls,filename,message):
cls.writelog(filename,message,"warn")
@classmethod
def Error(cls,filename,message):
cls.writelog(filename,message,"error")
@classmethod
def Critical(cls,filename,message):
cls.writelog(filename,message,"critical")
有不妥之处,希望大家指出。