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("\n")
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...')

如上,实现每天一个日志文件。

相关文章:

  • 2021-03-12
  • 2022-01-17
  • 2022-01-20
  • 2021-09-26
  • 2021-12-24
  • 2021-12-05
  • 2021-12-26
猜你喜欢
  • 2022-12-23
  • 2021-12-02
  • 2021-07-14
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案