1 _filefmt=os.path.join("logs","%Y-%m-%d.log") 2 class MyLoggerHandler(logging.Handler): 3 def __init__(self,filefmt=None): 4 self.filefmt=filefmt 5 if filefmt is None: 6 self.filefmt=_filefmt 7 logging.Handler.__init__(self) 8 def emit(self,record): 9 msg=self.format(record) 10 _filePath=datetime.datetime.now().strftime(self.filefmt) 11 _dir=os.path.dirname(_filePath) 12 try: 13 if os.path.exists(_dir) is False: 14 os.makedirs(_dir) 15 except Exception: 16 print("can not make dirs") 17 print("filepath is "+_filePath) 18 pass 19 try: 20 _fobj=open(_filePath,'a') 21 _fobj.write(msg) 22 _fobj.write(" ") 23 _fobj.flush() 24 _fobj.close() 25 except Exception: 26 print("can not write to file") 27 print("filepath is "+_filePath) 28 pass 29 if __name__ == '__main__': 30 logging.basicConfig() 31 logger = logging.getLogger("logger") 32 logger.setLevel(logging.INFO) 33 filehandler = MyLoggerHandler() 34 logger.addHandler(filehandler) 35 logger.info('log...')
如上,实现每天一个日志文件。