我正在尝试创建一个名为Package
的自定义类,该类具有日志记录功能。
import logging
logger = logging.getLogger('console')
class Package(logging.Logger):
def __enter__(self):
return self
def __exit__(self,exc_type,exc_val,exc_tb):
pass
def __init__(self,**kwargs):
pass
with Package() as p:
p.error('test')
由于某种原因,当我使用任何日志记录功能时,都会收到此错误消息:
Traceback (most recent call last):
File "test.py", line 14, in <module>
p.error('test')
File "C:\Program Files\Python36\lib\logging\__init__.py", line 1334, in error
if self.isEnabledFor(ERROR):
File "C:\Program Files\Python36\lib\logging\__init__.py", line 1548, in isEnabledFor
return level >= self.getEffectiveLevel()
File "C:\Program Files\Python36\lib\logging\__init__.py", line 1537, in getEffectiveLevel
if logger.level:
AttributeError: 'Package' object has no attribute 'level'
答案 0 :(得分:1)
您的代码有几个问题。
要正确初始化基类logger.Logger
,您需要调用它的__init__()
方法。例如:
class Package(logging.Logger):
def __init__(self, name, *args, **kwargs):
logging.Logger.__init__(self, name, *args, **kwargs)
基础logging.Logger
类需要一个名称,因此您需要给您的日志记录对象一个名称。例如:
with Package("test") as p:
p.error("test")
因此,上面的代码段如下所示:
import logging
logger = logging.getLogger('console')
class Package(logging.Logger):
def __init__(self, name, *args, **kwargs):
logging.Logger.__init__(self, name, *args, **kwargs)
def __enter__(self):
return self
def __exit__(self,exc_type,exc_val,exc_tb):
pass
with Package("test") as p:
p.error('test')
如果运行此命令,由于尚未为日志记录类定义处理程序,您仍然会收到错误消息,但是您可以在此处找到有关日志记录处理程序的更多信息:https://docs.python.org/2/howto/logging.html#handlers。