【问题标题】:Python Logging - Prevent log events from being printed to the consolePython Logging - 防止日志事件被打印到控制台
【发布时间】:2016-04-28 05:41:15
【问题描述】:

当我没有定义控制台处理程序时,我无法弄清楚为什么将日志事件打印到控制台。我阅读的所有示例都明确定义了一个控制台处理程序(streamhandler),以便将消息打印到控制台。

我希望仅将这些事件打印到文件中。

import logging
logger = logging.getLogger(__name__)

my_format = '%(asctime)-25s  %(levelname)-8s  LOGGER: %(name)-12s  MODULE: %(module)-15s FUNCTION: %(funcName)-30s MSG: %(message)s'
my_datefmt ='%m/%d/%Y %I:%M:%S%p'
logging.basicConfig(format=my_format, datefmt=my_datefmt, level=logging.DEBUG)
formatter = logging.Formatter(my_format, datefmt=my_datefmt)
logger.setLevel(logging.DEBUG)
handler1 = logging.FileHandler('mylog.txt')
handler1.setLevel(logging.DEBUG)
handler1.setFormatter(formatter)
logger.addHandler(handler1)

logger.debug("Why is this printed to the console")

编辑:

有人指出我没有考虑根记录器。在调用 logging.basicConfig 时,会将默认流处理程序添加到根记录器 (logger = getLogger())

可以修改根记录器的处理程序,但是我发现我可以阻止我的记录器将日志传播到根记录器。

可以这样做:

import logging
logger = logging.getLogger(__name__)

my_format = '%(asctime)-25s  %(levelname)-8s  LOGGER: %(name)-12s  MODULE: %(module)-15s FUNCTION: %(funcName)-30s MSG: %(message)s'
my_datefmt ='%m/%d/%Y %I:%M:%S%p'
logging.basicConfig(format=my_format, datefmt=my_datefmt, level=logging.DEBUG)
formatter = logging.Formatter(my_format, datefmt=my_datefmt)
logger.setLevel(logging.DEBUG)
handler1 = logging.FileHandler('mylog.txt')
handler1.setLevel(logging.DEBUG)
handler1.setFormatter(formatter)
logger.addHandler(handler1)
logger.propagate = False             ####
logger.debug("Why is this printed to the console")

【问题讨论】:

  • 谢谢!快速参考:您所做的唯一补充是:logger.propagate = False

标签: python logging


【解决方案1】:
> ipython
import logging
logging.basicConfig?

*****************logging.basicConfig**************
Signature: logging.basicConfig(**kwargs)
Docstring:
Do basic configuration for the logging system.

This function does nothing if the root logger already has handlers
configured. It is a convenience method intended for use by simple scripts
to do one-shot configuration of the logging package.

The default behaviour is to create a StreamHandler which writes to
sys.stderr, set a formatter using the BASIC_FORMAT format string, and
add the handler to the root logger.
...

您有 2 个处理程序。

【讨论】:

  • 感谢您的回答。
  • 不客气... errr 谁的名字不能说。
猜你喜欢
  • 1970-01-01
  • 2020-01-04
  • 2020-03-17
  • 2016-03-22
  • 1970-01-01
  • 2020-07-05
  • 2020-03-17
  • 2015-10-28
  • 1970-01-01
相关资源
最近更新 更多