![](/img/trans.png)
[英]Using logging.info instead of logger.info wrecks StreamHandler
[英]Python: What are differences between `logger.info` and `logging.info`?
我想知道下面两个版本之间有什么区别? 以及如何有效地使用它?
版本 1:
import logging
logging.info("Hello world!")
版本 2:
import logging
logger = logging.getLogger(__name__)
logger.info("Hello world!")
使用logging.getLogger(__name__)
(或任何更多自定义名称)的优点是日志将显示记录器的名称,在本例中为模块的名称,在您的日志中,您可以轻松区分哪个模块导致了哪个消息。 此外,您可以在中央配置文件的某处有选择地配置特定模块的日志,例如:
logging.getLogger('that.module.name').setLevel(logging.INFO)
例如,如果您将常规日志记录级别设置为DEBUG
,但某处有一个非常嘈杂的模块会导致大量多余的 output,您可以选择性地抑制它。
我运行我的代码:
class TestBedLog():
async def test(self):
import logging
logging.info("Log from logging")
logger = logging.getLogger(__name__)
logger.info("Log from logger")
结果是:
root: INFO: Log from logging
src.myserver.test.test_apiv2.test_bedlog: INFO: Log from logger
如您所见, logging
来自root
。 并且logger
您将看到记录信息的文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.