如何在 Python 中获取包含日志记录调用的类的名称?

新手上路,请多包涵

如果我想要函数名称,我可以简单地将 %(funcName)s 包含在 Formatter 中。但是我如何获取包含日志记录调用的类的名称呢?

我已经浏览了 logging 的文档,但我找不到任何提及它的地方。

原文由 c00kiemonster 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 578
1 个回答

要获得类名以使用记录器输出的一种相当简单的 pythonic 方法,只需使用日志记录类。

 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()

原文由 kylehuff 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题