登录Python。处理程序和控制台副本

登录Python。处理程序和控制台副本,python,logging,Python,Logging,我有一个简单的日志设置: 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.FileHand

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

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.log
info.log
文件只包含正确级别的消息,但它们的格式不包括前缀
info:\uuuu main\uuu
debug:\uu main\uu
。为什么它们的格式不同

logging.basicConfig(filemode='w', level=logging.DEBUG)
创建
流处理程序
。因此,您的代码正在创建两个
streamhandler
,一个具有日志级别
DEBUG
,另一个具有级别
INFO

basicConfig
是一个方便的功能。如果要创建自己的处理程序,则无需调用
basicConfig
。(或者您可以调用
basicConfig
并添加其他处理程序…)


如果在调用
basicConfig
时未提供文件名,则将
StreamHandler
添加到根记录器。代码如下:


为什么设置level=DEBUG,我总是使用
logging.basicConfig(format='%(asctime)s%(message)s')
也要记住,记录器实例是单例的,所以设置2个处理程序可能会使它在两个级别重复消息,即INFO和DEBUG。
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)