Python:如何禁止来自第三方库的日志记录语句? [英] Python: how to suppress logging statements from third party libraries?

查看:952
本文介绍了Python:如何禁止来自第三方库的日志记录语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的日志记录设置如下

import requests
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('BBProposalGenerator')

运行此命令时,我得到的日志为

When I run this, I get logs as

INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): localhost
INFO:BBProposalGenerator:created proposal: 763099d5-3c8a-47bc-8be8-b71a593c36ac
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): localhost
INFO:BBProposalGenerator:added offer with cubeValueId: f23f801f-7066-49a2-9f1b-1f8c64576a03
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): localhost
INFO:BBProposalGenerator:evaluated proposal: 763099d5-3c8a-47bc-8be8-b71a593c36ac

如何抑制requests包中的日志语句?这样我只能看到我的代码中的日志

How can I suppress the log statements from requests package? so that I only see logs from my code

INFO:BBProposalGenerator:created proposal: 763099d5-3c8a-47bc-8be8-b71a593c36ac
INFO:BBProposalGenerator:added offer with cubeValueId: f23f801f-7066-49a2-9f1b-1f8c64576a03
INFO:BBProposalGenerator:evaluated proposal: 763099d5-3c8a-47bc-8be8-b71a593c36ac

谢谢

推荐答案

您以logging.INFO级别调用了basicConfig(),该级别将root记录器和所有后继记录器的有效级别设置为INFO没有明确设置级别.其中包括requests记录器,并说明了为什么获得这些结果.

You called basicConfig() with a level of logging.INFO, which sets the effective level to INFO for the root logger, and all descendant loggers which don't have explicitly set levels. This includes the requests loggers, and explains why you're getting these results.

相反,您可以这样做

logging.basicConfig()

会将级别保留为默认值WARNING,但是添加了一个将日志消息输出到控制台的处理程序.然后,将记录器上的级别设置为INFO:

which will leave the level at its default value of WARNING, but add a handler which outputs log messages to the console. Then, set the level on your logger to INFO:

logger = logging.getLogger('BBProposalGenerator')
logger.setLevel(logging.INFO)

现在,将打印记录到记录器BBProposalGenerator或其任何后代的严重性更高的事件,但根记录器(及其其他后代,例如requests.XXX)将保留在WARNING级别,仅显示WARNING或更高级别的消息.

Now, INFO and higher severity events logged to logger BBProposalGenerator or any of its descendants will be printed, but the root logger (and other descendants of it, such as requests.XXX) will remain at WARNING level and only show WARNING or higher messages.

当然,您可以在basicConfig()调用中指定更高的级别-例如,如果指定了ERROR,则从所有其他记录器中只能看到ERROR或更高,但是INFO或更高来自BBProposalGenerator及其后代.

Of course, you can specify a higher level in the basicConfig() call - if you specified ERROR, for example, you would only see ERROR or higher from all the other loggers, but INFO or higher from BBProposalGenerator and its descendants.

这篇关于Python:如何禁止来自第三方库的日志记录语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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