這次的代碼就是一個日志記錄模塊,代碼很容易懂,注釋很詳細,也不需要安裝什么庫。提供的功能是日志可以顯示在屏幕上並且保存在日志文件中。
調用的方式也很簡單,測試代碼里面有。
源代碼:
#encoding=utf-8 import logging import getpass import sys # 定義MyLog類 class MyLog(object): # 類MyLog的構造函數 def __init__(self): self.user = getpass.getuser() self.logger = logging.getLogger(self.user) self.logger.setLevel(logging.DEBUG) # 日志文件名 self.logFile = sys.argv[0][0:-3] + '.log' #print(sys.argv[0]) 代表文件名 輸出 mylog.py self.formatter = logging.Formatter('%(asctime)-12s %(levelname)-8s %(name)-10s %(message)-12s\r\n') # 日志顯示到屏幕上並輸出到日志文件內 # 輸出到日志文件 self.logHand = logging.FileHandler(self.logFile, encoding='utf8') self.logHand.setFormatter(self.formatter) self.logHand.setLevel(logging.DEBUG) # 輸出到屏幕 self.logHandSt = logging.StreamHandler() self.logHandSt.setFormatter(self.formatter) self.logHandSt.setLevel(logging.DEBUG) # 添加兩個Handler self.logger.addHandler(self.logHand) self.logger.addHandler(self.logHandSt) # 日志的5個級別對應以下的5個函數 def debug(self,msg): self.logger.debug(msg) def info(self,msg): self.logger.info(msg) def warning(self,msg): self.logger.warning(msg) def error(self,msg): self.logger.error(msg) def critical(self,msg): self.logger.critical(msg) if __name__ == '__main__': mylog = MyLog() mylog.debug(u"I'm debug 測試中文") mylog.info("I'm info") mylog.warning("I'm warn") mylog.error(u"I'm error 測試中文") mylog.critical("I'm critical")
測試結果: