![](/img/trans.png)
[英]Python Logging with a common logger class mixin and class inheritance
[英]attach common python logging snippet to different class definition?
尝试将一个常见代码段附加到不同的类中以进行日志记录/调试如下所示:
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()
该代码以某种方式工作,但是很丑陋:
"name"
甚至"LongNameClass.name"
获取类名不起作用 “LongNameClass.dbg.info”
不易于键入和阅读,需要更短“LongNameClass.dbg.info”
常见的内容... 任何人都可以展示改进样本吗? 谢谢。
我仍然不太确定ClassDescriptorHelper
和DebugHelper
类的情况,但是假设您要自动向每个类添加记录器,我将查看注释/修饰符 。
>>> 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
>>>
如果尝试访问实例的属性(例如self.dbg
),它将首先查看其自己的实例变量,如果找不到,则将查看类的变量。 如果找不到它,它将继续查找继承树(新旧样式类之间略有不同)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.