找不到记录器的处理程序 [英] No handlers could be found for logger
问题描述
我是 Python 的新手.我正在尝试登录 python 并且在尝试通过记录器实例打印一些警告时遇到找不到记录器的处理程序错误.下面是我试过的代码
导入日志logger=logging.getLogger('logger')logger.warning('系统可能崩溃')
我收到此错误找不到记录器logger"的处理程序
让我感到困惑的是,当我第一次尝试使用 logging
打印警告,然后通过 logger
时,它工作正常,就像
有人可以对第二种情况中发生的事情有所了解吗?
对于通过 logger
记录一些消息,在 Python 中至少应该添加一个处理程序到 logger
目的.默认情况下,logging
模块中的 debug
、warn
和其他函数将调用 basicConfig
,后者又会添加一个 StreamHandler
到 root logger
.
总是推荐将您需要的处理程序添加到您正在编写的记录器对象中你的模块.
您可以参考官方 Python 文档,其中有一个 很棒的教程 或者你可以自己查看日志模块的源代码.
您只需通过以下方式检查 Python shell 中的源代码
导入日志进口检验打印(inspect.getsource(日志记录))
最后,显式调用 basicConfig
将解决问题.
导入日志logging.basicConfig()logger = logging.getLogger('logger')logger.warning('系统可能崩溃')
I am newbie to python. I was trying logging in python and I came across No handlers could be found for logger error while trying to print some warning through logger instance. Below is the code I tried
import logging
logger=logging.getLogger('logger')
logger.warning('The system may break down')
And I get this error No handlers could be found for logger "logger"
What's confusing me is when I first try to print warning using logging
and then through logger
, it works fine, like
>>> import logging
>>> logging.warning('This is a WARNING!!!!')
WARNING:root:This is a WARNING!!!!
>>>
>>> logger.warning('WARNING!!!!')
WARNING:logger:WARNING!!!!
Can someone throw some light on what's happening in second scenario?
For logging some message through logger
, in Python at least one handler should be added to the logger
object. By default the debug
, warn
and other functions in logging
module will call basicConfig
which in turn will add a StreamHandler
to the root logger
.
It's always recommended to add your required Handler to your logger object you are writing for your module.
You could refer to official Python docs, which has an awesome tutorial or you can better check out the source code of logging module yourself.
Simply you can check the source in Python shell itself by,
import logging
import inspect
print(inspect.getsource(logging))
Finally, calling the basicConfig
explicitly will resolve the issue.
import logging
logging.basicConfig()
logger = logging.getLogger('logger')
logger.warning('The system may break down')
这篇关于找不到记录器的处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!