Below for you to share a Python implementation of the log log sample code, has a good reference value, I hope to help you. Come and see it together.
# coding=utf-8import Loggingimport osimport timelevels={' Debug ': Logging. Debug,\ ' info ': logging.info,\ ' warning ': Logging. Warning,\ ' ERROR ': Logging. Error,\ ' critical ': logging. Critical,}logger=logging.getlogger () level= ' default ' def createFile (filename): Path=filename[0:filename.rfind ('/') ] If not Os.path.isdir (path): os.makedirs (path) if not os.path.isfile (filename): #创建并打开一个新文件 fd = open (filename,mode= ' W ', encoding= ' Utf-8 ') fd.close () class mylog:log_filename= ' E:/quality/it/pyrequest-master/log/itest.log ' err_filename= ' E:/quality/it/pyrequest-master/log/err.log ' dateformat= '%y-%m-%d%h:%m:%s ' Logger.setlevel (LEVELS.get (level, Logging. NOTSET)) CreateFile (log_filename) createFile (err_filename) #注意文件内容写入时编码格式指定 handler=logging. Filehandler (log_filename,encoding= ' utf-8 ') errhandler=logging. Filehandler (err_filename,encoding= ' utf-8 ') @staticmethod #静态方法 def debug (log_message): SetHandler (' Debug ') Logger.debug ("[Debug" +getcurrenttime () + "]" +log_message) removerhandler (' Debug ') @staticmethoD def info (log_message): SetHandler (' info ') logger.info ("[Info" +getcurrenttime () + "]" +log_message) Removerhandler (' Info ') @staticmethod def Warning (log_message): SetHandler (' warning ') logger.warning ("[Warning" +getcurrenttime () + "]" +log_message) Removerhandler (' warning ') @staticmethod def error (Log_message): SetHandler (' Error ') Logger.error ("[ Error "+getcurrenttime () +"] "+log_message) Removerhandler (' Error ') @staticmethod def Critical (log_message): SetHandler (' critical ') logger.critical ("[Critical" +getcurrenttime () + "]" +log_message) Removerhandler (' critical ') # Logger can be seen as a log person, for every log recorded, he needs a set of rules, such as the format of the record (formatter), # level, and so on, this rule is handler. Using Logger.addhandler (handler) to add multiple rules, # You can have one logger log multiple logs. def setHandler (level): If level== ' Error ': Logger.addhandler (Mylog.errhandler) #handler =logging. Filehandler (log_filename) #把logger添加上handler Logger.addhandler (Mylog.handler) def Removerhandler (level): If level== ' Error ': Logger.removehandler (Mylog.errhandler) Logger.removehandler (MYlog.handler) def getcurrenttime (): Return Time.strftime (Mylog.dateformat,time.localtime (Time.time ())) if __name__== "__main__": Mylog.debug ("This is the Debug message") Mylog.info ("This is the info message") mylog.warning ("This is warning message ") Mylog.error (" This is the error message ") mylog.critical (" This is critical message ")