首页 > 编程语言 > 详细

python自定义logger handler

时间:2016-01-07 10:17:50      阅读:557      评论:0      收藏:0      [点我收藏+]
 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...)

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

python自定义logger handler

原文:http://www.cnblogs.com/cero/p/5108786.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!