在python2中正常的日志,单只直接使用python3,发现日志重复了,其实是handlers多添加的原因,

python2代码

-----------------------------------------------------------------------------------------------------------------------------------------------------------

 def my_log(msg):

         if logging.getLogger('log.log'):

                return logging.getLogger('log.log')

 

         logger = logging.getLogger('log.log')

         ch = logging.StreamHandler()

         ch.setLevel(logging.ERROR)

         fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

         ch.setFormatter(fmt)

         logger.addHandler(ch) logger.error(msg)


-----------------------------------------------------------------------------------------------------------------------------------------------------------

适当修改一下:

python3代码:
-----------------------------------------------------------------------------------------------------------------------------------------------------------

 def my_log(msg):

         if logging.getLogger('log.log'):

                return logging.getLogger('log.log')

         logger = logging.getLogger('log.log')

        if  not logger.handlers:

             ch = logging.StreamHandler()

             ch.setLevel(logging.ERROR)

             fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

             ch.setFormatter(fmt)

             logger.addHandler(ch) logger.error(msg)
-----------------------------------------------------------------------------------------------------------------------------------------------------------

加一个重复判断就行