您好,登錄后才能下訂單哦!
這篇文章主要介紹python如何實現(xiàn)log日志,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!
源代碼:
# coding=utf-8 import logging import os import time LEVELS={'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): #創(chuàng)建并打開一個新文件 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) #注意文件內(nèi)容寫入時編碼格式指定 handler=logging.FileHandler(log_filename,encoding='utf-8') errhandler=logging.FileHandler(err_filename,encoding='utf-8') @staticmethod #靜態(tài)方法 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可以看做是一個記錄日志的人,對于記錄的每個日志,他需要有一套規(guī)則,比如記錄的格式(formatter), # 等級(level)等等,這個規(guī)則就是handler。使用logger.addHandler(handler)添加多個規(guī)則, # 就可以讓一個logger記錄多個日志。 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 debug message") MyLog.info("This is info message") MyLog.warning("This is warning message") MyLog.error("This is error message") MyLog.critical("This is critical message")
以上是“python如何實現(xiàn)log日志”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。