美文网首页
python3.2使用logging不能打印log日志及打印出重

python3.2使用logging不能打印log日志及打印出重

作者: Dynasty鑫 | 来源:发表于2018-12-17 10:19 被阅读0次

    在python3.6中,我们使用logging时还是用logging.basicConfig(level=logging.INFO,format='', filename=name.log, filemode='a')的方式创建写入日志文件,但是在python3.2中这个就显得行不通了,
    首先它会出现无法打印日志文件的情况,那么就要使用下面这个写法:
    import logging
    logger = logging.getLogger()
    hdlr = logging.FileHandler('name.log')
    logger.addHandler(hdlr)
    logger.setLevel(logging.INFO)
    logger.info('this is info')
    输出结果为:‘this is info’
    如果是在定时执行的情况下,就会出现重复打印的情况:
    第一次执行:this is info
    第二次执行:this is info
    this is info
    第三次执行:this is info
    this is info
    this is info
    那么这是因为:当第二次调用log的时候,根据getLogger()会获取同一个logger,而这个logger里已经有了第一次你添加的hdlr,第二次调用又添加了一个hdlr,也就是说这个logger里有了两个同样的hdlr,所以就会出现调用几次就会有几个hdlr

    那么下面说道解决方案:在最后添加一句logger.handlers.pop()就能解决问题,切记在最后,最后,最后

    相关文章

      网友评论

          本文标题:python3.2使用logging不能打印log日志及打印出重

          本文链接:https://www.haomeiwen.com/subject/wahqkqtx.html