登录Python.句柄和控制台重复



我有一个简单的日志设置:

def main()
  # ....
  # Create logger
  logging.basicConfig(filemode='w', level=logging.DEBUG)
  logger = logging.getLogger(__name__)
  logger.setLevel(logging.DEBUG)
  # Create file handler for DEBUG and above
  fh1 = logging.FileHandler(__name__ + '.debug.log')
  fh1.setLevel(logging.DEBUG)
  # Create file handler for INFO and above
  fh2 = logging.FileHandler(__name__ + '.info.log')
  fh2.setLevel(logging.INFO)
  # Create console handler with INFO and above
  ch = logging.StreamHandler()
  ch.setLevel(logging.INFO)
  # Add all the handlers to the logger
  logger.addHandler(fh1)
  logger.addHandler(fh2)
  logger.addHandler(ch)
  # ....

然后当我打电话给

logger.info("this is an INFO message")
logger.debug("this is a DEBUG message")

我在控制台上得到以下内容:

this is an INFO message
INFO:__main__:this is an INFO message
this is a DEBUG message
DEBUG:__main__:this is a DEBUG message

尽管我希望在控制台中只看到INFO消息(因为我在上面为StreamHandler指定了logging.info(。为什么我要得到这些副本?

我的.debug.loginfo.log文件只包含正确级别的消息,但它们的格式不包括前缀INFO:__main__DEBUG:__main__。为什么它们的格式不同?

logging.basicConfig(filemode='w', level=logging.DEBUG)

创建CCD_ 8。因此,您的代码正在创建两个StreamHandlers,一个具有日志级别DEBUG,另一个具有级别INFO

CCD_ 12是一个方便函数。如果要创建自己的处理程序,则不必调用basicConfig。(或者您可以调用basicConfig并添加其他处理程序…(


如果在对basicConfig的调用中没有提供文件名,则会向根记录器中添加一个StreamHandler。这是basicConfig函数中的代码:

if handlers is None:
    filename = kwargs.get("filename")
    if filename:
        mode = kwargs.get("filemode", 'a')
        h = FileHandler(filename, mode)
    else:
        stream = kwargs.get("stream")
        h = StreamHandler(stream)

最新更新