登录Python.处理程序和控制台重复项 [英] Logging in Python. Handlers and console duplicates

查看:33
本文介绍了登录Python.处理程序和控制台重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple logging setup:

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")

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

I get the following on the console:

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 ).为什么我会得到这些重复项?

Even though I expected to only see INFO messages in the console (since I specified logging.info above for the StreamHandler). Why do I get these duplicates?

我的 .debug.log info.log 文件仅包含正确级别的消息,但其格式不包括首选项 INFO:__ main__ DEBUG:__ main __ .为什么它们的格式不同?

My .debug.log and info.log files contain only the messages at the right level, but their formatting does not include the prefices INFO:__main__ nor DEBUG:__main__. Why is their formatting different?

推荐答案

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

创建一个 StreamHandler .因此,您的代码正在创建两个 StreamHandlers ,一个具有日志记录级别 DEBUG ,另一个具有日志记录级别 INFO .

creates a StreamHandler. So your code is creating two StreamHandlers, one with logging level DEBUG and another with level INFO.

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

basicConfig is a convenience function. If you want to create your own handlers, it is not necessary to call basicConfig. (Or you can call basicConfig and add additional handlers...)

如果在对 basicConfig 的调用中未提供文件名,则会将 StreamHandler 添加到根记录器.这是 basicConfig >功能:

If you don't supply a filename in the call to basicConfig, then a StreamHandler is added to the root logger. This is the code inside the basicConfig function:

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)

这篇关于登录Python.处理程序和控制台重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆