[英]Python Logging - Prevent log events from being printed to the console
I can't figure out why log events are being printed to the console when I have not defined a console handler. 在我没有定义控制台处理程序时,我无法弄清楚为什么日志事件正在打印到控制台。 All of the examples I read through have explicitly defined a console handler (streamhandler) in order to print messages to the console.
我读过的所有示例都明确定义了一个控制台处理程序(streamhandler),以便将消息打印到控制台。
I want these events to be printed to a file only. 我希望这些事件只打印到文件中。
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")
EDIT: 编辑:
It has been pointed out that I was not considering the root logger. 有人指出我没有考虑根记录器。 Upon calling logging.basicConfig, a default streamhandler is added to the root logger (logger = getLogger())
在调用logging.basicConfig时,会将一个默认的streamhandler添加到根记录器(logger = getLogger())
The root logger's handler can be modified, however I have found that I can just prevent my logger from propagating logs up to the root logger. 根记录器的处理程序可以修改,但我发现我可以阻止我的记录器将日志传播到根记录器。
This can be done like so: 这可以这样做:
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")
> 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.
...
You have 2 handlers. 你有2个处理程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.