如何在Python中禁用并重新启用控制台日志记录? [英] How to I disable and re-enable console logging in Python?

查看:586
本文介绍了如何在Python中禁用并重新启用控制台日志记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是python 记录模块,我想禁用控制台日志记录一些时间,但它不工作。

I am using python logging module and I want to disable the console logging for some time but it doesn't work.


  #!/usr/bin/python
  import logging

  logger = logging.getLogger() # this gets the root logger
  # ... here I add my own handlers 
  #logger.removeHandler(sys.stdout)
  #logger.removeHandler(sys.stderr)

  print logging.handlers 
  # this will print [<logging.StreamHandler instance at ...>]
  # but I may have other handlers there that I want to keep

  logger.debug("bla bla")

上面的代码在stdout上显示bla bla,我不知道如何安全地禁用控制台处理程序。

The above code displays the "bla bla" on stdout and I don't know how can I safely disable the console handler. How can I bu sure that I temporary remove the console streamhandler and not another one?

推荐答案

我发现了一个解决方案:

I found a solution for this:

logger = logging.getLogger('my-logger')
logger.propagate = False
# now if you use logger it will not log to console.

这将阻止将日志记录发送到包含控制台日志记录的上层记录器。

This will prevent logging from being send to the upper logger that includes the console logging.

这篇关于如何在Python中禁用并重新启用控制台日志记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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