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

c00*_*ter 15 python logging class

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

我已经阅读了文档logging,但我找不到任何提及它.

kyl*_*uff 12

要获得使用记录器输出类名的相当简单,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()
Run Code Online (Sandbox Code Playgroud)

通过如上所述命名记录器,%(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
Run Code Online (Sandbox Code Playgroud)

备择方案)

非遗传

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()
Run Code Online (Sandbox Code Playgroud)


Moh*_*ari 5

您应该使用额外的参数:

views.py

import logging

class SampleClass():
    def sample_func(self):
        logging.getLogger('info_logger').info('some text', extra={'className': self.__class__.__name__})
Run Code Online (Sandbox Code Playgroud)

logger_settings.py

'format': '%(className)s | %(message)s ',
Run Code Online (Sandbox Code Playgroud)

输出日志:

INFO | SampleClass | "some text" 
Run Code Online (Sandbox Code Playgroud)


ed.*_*ed. 2

几乎可以肯定有一种更好的方法可以做到这一点,但是直到有人指出这一点之前,这都会起作用:

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()
Run Code Online (Sandbox Code Playgroud)

其输出如下:

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']
Run Code Online (Sandbox Code Playgroud)