python 记录日志logging
在项目开发中,往往要记录日志文件。用python记录日志有两种方式:
1、利用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)
2、自己写日志
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