编程语言
首页 > 编程语言> > python自定义logger handler

python自定义logger handler

作者:互联网

_filefmt=os.path.join("logs","%Y-%m-%d.log")
class MyLoggerHandler(logging.Handler):
    def __init__(self,filefmt=None):
        self.filefmt=filefmt
        if filefmt is None:
            self.filefmt=_filefmt
        logging.Handler.__init__(self)
    def emit(self,record):
        msg=self.format(record)
        _filePath=datetime.datetime.now().strftime(self.filefmt)
        _dir=os.path.dirname(_filePath)
        try:
            if os.path.exists(_dir) is False:
                os.makedirs(_dir)
        except Exception:
            print("can not make dirs")
            print("filepath is "+_filePath)
            pass
        try:
            _fobj=open(_filePath,'a') 
            _fobj.write(msg)
            _fobj.write("\n")
            _fobj.flush()
            _fobj.close()
        except Exception:
            print("can not write to file")
            print("filepath is "+_filePath)
            pass
if __name__ == '__main__':
    logging.basicConfig()
    logger = logging.getLogger("logger")
    logger.setLevel(logging.INFO)
    filehandler = MyLoggerHandler()
    logger.addHandler(filehandler)
    logger.info('log...')

标签:__,filefmt,自定义,filePath,python,self,fobj,logger
来源: https://www.cnblogs.com/ExMan/p/11284276.html