import logging
# Create a base class
class LoggingHandler:
def __init__(self, *args, **kwargs):
self.log = logging.getLogger(self.__class__.__name__)
# Create test class A that inherits the base class
class testclassa(LoggingHandler):
def testmethod1(self):
# call self.log.<log level> instead of logging.log.<log level>
self.log.error("error from test class A")
# Create test class B that inherits the base class
class testclassb(LoggingHandler):
def testmethod2(self):
# call self.log.<log level> instead of logging.log.<log level>
self.log.error("error from test class B")
testclassa().testmethod1()
testclassb().testmethod2()
通过如上所述命名记录器,%(name)s将是类的名称
示例输出
$ python mymodule.py
[2016-02-03 07:12:25,624] ERROR [testclassa.testmethod1:29] error from test class A
[2016-02-03 07:12:25,624] ERROR [testclassb.testmethod2:36] error from test class B
备选方案
不继承
import logging
def log(className):
return logging.getLogger(className)
class testclassa:
def testmethod1(self):
log(self.__class__.__name__).error("error from test class A")
class testclassb:
def testmethod2(self):
log(self.__class__.__name__).error("error from test class B")
testclassa().testmethod1()
testclassb().testmethod2()
我个人倾向于在课后给我的记录者起名字,因为这样可以更容易地追踪特定信息的来源。所以您可以有一个名为“top”的根日志记录器,对于模块“a”和类“testclass”,我将我的日志记录器命名为“top.a.testclass”。
我不认为需要另外检索类名,因为日志消息应该提供您需要的所有信息。
@ed在上面的回应,让我觉得很不符合语法,而且我也不愿意在生产代码中使用它。
几乎可以肯定,有更好的方法可以做到这一点,但在有人指出这一点之前,这将是可行的:
其输出如下:
要想用日志记录器输出类名,使用一种相当简单的pythonic方法,只需使用一个日志类。
通过如上所述命名记录器,
%(name)s
将是类的名称示例输出
备选方案
不继承
相关问题 更多 >
编程相关推荐