Python Logger打印两次

时间:2018-02-06 13:20:21

标签: python logging

这是我的代码,它是两次打印日志 ```

def get_logger(name, verbose=False):
  # create logger
  logger = logging.getLogger(name)

  # create console handler and set level to debug
  ch = logging.StreamHandler()

  if verbose:
      logger.setLevel(logging.DEBUG)
      ch.setLevel(logging.DEBUG)
  else:
      logger.setLevel(logging.INFO)
      ch.setLevel(logging.INFO)

  # create formatter
  formatter = logging.Formatter('%(asctime)s : [%(name)s] : %(levelname)s : %(message)s')

  # add formatter to ch
  ch.setFormatter(formatter)

  # add ch to logger
  logger.addHandler(ch)
  return logger

```

不确定为什么在屏幕上打印两次。这有什么不对?

1 个答案:

答案 0 :(得分:0)

确定。因此记录器中需要进行一些小的更改才能解决问题。这是新代码: ```

   def get_logger(self):
        # create logger
        logger = logging.getLogger(self.name)
        logger.propagate = False  #### ------- ADDED --------- #####

        # create console handler and set level to debug
        ch = logging.StreamHandler()

        if self.verbose:
            logger.setLevel(logging.DEBUG)
            ch.setLevel(logging.DEBUG)
        else:
            logger.setLevel(logging.INFO)
            ch.setLevel(logging.INFO)

        # create formatter
        formatter = logging.Formatter('%(asctime)s : [%(name)s] : %(levelname)s : %(message)s')

        # add formatter to ch
        ch.setFormatter(formatter)

        # add ch to logger
        logger.addHandler(ch)
        return logger

```