是否将公共python日志记录片段附加到不同的类定义?
尝试将一个公共代码段附加到不同的类中以进行日志记录/调试,如下所示:是否将公共python日志记录片段附加到不同的类定义?,python,class,templates,logging,Python,Class,Templates,Logging,尝试将一个公共代码段附加到不同的类中以进行日志记录/调试,如下所示: import logging logging.basicConfig(level=logging.INFO) class ClassDescriptorHelper(object): def __get__(self, instance, owner): return owner.__name__ class DebugHelper(object): def __init__(self, l
import logging
logging.basicConfig(level=logging.INFO)
class ClassDescriptorHelper(object):
def __get__(self, instance, owner):
return owner.__name__
class DebugHelper(object):
def __init__(self, logger_str= "UNDEFINED_DEFAULT", logging_=logging):
self.logger_ = logging_.getLogger(logger_str)
class LongNameClass():
#===========================HEAD================================
name = ClassDescriptorHelper()
#dbghlp = DebugHelper(logger_str= name ) # A) not working here, LongNameClass.name also not working
dbghlp = DebugHelper(logger_str="LongNameClass") # A) working, but ugly, have to key in "string" for different class
dbg = dbghlp.logger_
#===========================HEAD================================
def test_debug(self):
LongNameClass.dbg.info('Sample of Logging info') ## B) working, but required typing of class name
print LongNameClass.name # A) working
foo = LongNameClass()
foo.test_debug()
代码以某种方式工作,但很难看:
- A) 尝试使用代码
或甚至“name”
获取类名 工作“LongNameClass.name”
- B) 对于类内方法的使用,
是 不容易打字和阅读,想要一些简短和普通的“LongNameClass.dbg.info”
有人能出示改进样品吗?谢谢。我仍然不能完全确定
ClassDescriptorHelper
和DebugHelper
类发生了什么,但是假设您想自动向每个类添加一个记录器,我会看看
如果您试图访问实例的属性(例如
self.dbg
),它将首先查看自己的实例变量,如果找不到实例变量,它将查看类的变量。如果在那里找不到它,它将继续查找继承树(新旧样式类之间略有不同)。您应该能够使用self.dbg.info(…
。我不确定您使用类描述符RHELPER
和调试助手
classes@TrengotClassDescriptorHelper
尝试在类定义中为registergetLogger
自动使用类名,DebugHelper
尝试分离日志记录模块在类中添加代码以供后期使用,例如,使用其他日志记录,如module.and@Trengot,self.dbg.info
可以工作,与CLASSNAME.dbg.info
有什么不同吗?我的理解是self
意味着每个实例中都存在,CLASSNAME.dbg.info
意味着所有实例都是共享的,为什么self
可以工作类的名称也可以访问类变量。self.dbg
是与CLASSNAME.dbg
相同的对象,直到您重写它(通过执行类似于self.dbg=2
的操作)。
>>> import logging
>>> logging.basicConfig(level=logging.INFO)
>>> def add_log(cls):
... setattr(cls, 'dbg', logging.getLogger(cls.__name__))
... return cls
...
>>> @add_log
... class LongClassName:
... def test_info(self):
... self.dbg.info("helloWorld")
>>> x = LongClassName()
>>> x.test_info()
INFO:LongClassName:helloWorld
>>>