Python日志记录 - 防止将日志事件打印到控制台

时间:2016-01-21 19:42:47

标签: python logging

当我没有定义控制台处理程序时,我无法弄清楚为什么会在控制台上打印日志事件。我读过的所有示例都明确定义了一个控制台处理程序(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时,会将一个默认的streamhandler添加到根记录器(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")

1 个答案:

答案 0 :(得分:3)

> 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个处理程序。