通常狀況下,咱們在利用logging模塊記錄日誌的時候,每每會利用下面這種方式進行日誌信息的記錄:spa
import logging def logger_file(): #生成logger對象 whw_logger = logging.getLogger('whw.log') whw_logger.setLevel(logging.INFO) #生成handler對象 whw_fh = logging.FileHandler('whw.log') whw_fh.setLevel(logging.INFO) #生成Formatter對象 file_formatter = logging.Formatter(' %(asctime)s - %(name)s - %(levelname)s - %(message)s ') #把formatter對象綁定到handler對象中 whw_fh.setFormatter(file_formatter) # 把handler對象綁定到logger對象中 whw_logger.addHandler(whw_fh) return whw_logger if __name__ == '__main__': while 1: s = input('請輸入日誌信息:') logger_file().info(s)
生成的log日誌裏總會出現重複的同一條信息:日誌
咱們能夠再寫一個方法,將寫好的信息處理一下:code
def write_log(msg): log_obj = logger_file() log_obj.info(msg) log_obj.handlers.pop()
這樣,完整的代碼以下:orm
import logging def logger_file(): #生成logger對象 whw_logger = logging.getLogger('whw.log') whw_logger.setLevel(logging.INFO) #生成handler對象 whw_fh = logging.FileHandler('whw.log') whw_fh.setLevel(logging.INFO) #生成Formatter對象 file_formatter = logging.Formatter(' %(asctime)s - %(name)s - %(levelname)s - %(message)s ') #把formatter對象綁定到handler對象中 whw_fh.setFormatter(file_formatter) # 把handler對象綁定到logger對象中 whw_logger.addHandler(whw_fh) return whw_logger def write_log(msg): log_obj = logger_file() log_obj.info(msg) log_obj.handlers.pop() if __name__ == '__main__': while 1: s = input('請輸入日誌信息:') write_log(s)
對於一樣的輸入,咱們獲得的結果就沒有了重複信息:對象