在項目開發中,每每要記錄日誌文件。用python記錄日誌有兩種方式:python
一、利用python 自帶的logging庫,例如:函數
# -*- coding: utf-8 -*- import os import codecs import datetime import logging #封裝logging日誌 class LogFile: #構造函數 fileName:文件名 def __init__(self,fileName,level=logging.INFO): fh = logging.FileHandler(fileName) self.logger = logging.getLogger() self.logger.setLevel(level) formatter = logging.Formatter('%(asctime)s : %(message)s','%Y-%m-%d %H:%M:%S') fh.setFormatter(formatter) self.logger.addHandler(fh) def WriteLog(self,message): self.logger.info(message) def WriteErrorLog(self,message): self.logger.setLevel(logging.ERROR) self.logger.error(message)
二、本身寫日誌
import os import time class Log: def __init__(self): pass def WriteLog(self,message,flag = False): strMessage = '\n' + time.strftime('%Y-%m-%d %H:%M:%S') if flag: strMessage += ': %s' % message else: strMessage += ':\n%s' % message fileName = os.path.join(os.getcwd(), time.strftime('%Y-%m-%d')+ '.txt') with open(fileName, 'a',encoding='utf-8') as f:
f.write(strMessage)
# log = Log() # log.WriteLog('aaa') # 輸出結果: # 2017-11-24 10:39:52: # aaa # 2017-11-24 10:39:56:aaa