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

2024-10-02 00:43:39 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我想要函数名,我可以简单地在格式化程序中包含%(funcName)s。但是如何获得包含日志调用的类的名称呢?

我已经浏览了logging的文档,但找不到任何关于它的内容。


Tags: 函数文档程序名称内容loggingfuncname
3条回答

我个人倾向于在课后给我的记录者起名字,因为这样可以更容易地追踪特定信息的来源。所以您可以有一个名为“top”的根日志记录器,对于模块“a”和类“testclass”,我将我的日志记录器命名为“top.a.testclass”。

我不认为需要另外检索类名,因为日志消息应该提供您需要的所有信息。

@ed在上面的回应,让我觉得很不符合语法,而且我也不愿意在生产代码中使用它。

几乎可以肯定,有更好的方法可以做到这一点,但在有人指出这一点之前,这将是可行的:

import inspect

class testclass:
    def testmethod(self):
        log()

def log():
    stack = inspect.stack()
    try:
        print "Whole stack is:"
        print "\n".join([str(x[4]) for x in stack])
        print "-"*20
        print "Caller was %s" %(str(stack[2][4]))
    finally:
        del stack

testclass().testmethod()

其输出如下:

Whole stack is:
['    stack = inspect.stack()\n']
['        f()\n']
['testclass().testmethod()\n']
['                exec code in self.locals\n']
['            ret = method(*args, **kwargs)\n']
None
--------------------
Caller was ['testclass().testmethod()\n']

要想用日志记录器输出类名,使用一种相当简单的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()

相关问题 更多 >

    热门问题