如何获取Python中包含日志调用的类名?
如果我想要函数的名字,我可以在格式化器里简单地加上 %(funcName)s
。但是,我该怎么获取包含日志调用的类的名字呢?
我查阅了 logging
的文档,但没有找到相关的说明。
6 个回答
4
如果你还想要模块的名字,这里有另一种方法:
class MyClass(object):
@property
def logger(self):
return logging.getLogger(f"{__name__}.{self.__class__.__name__}")
def what(self, ever):
self.logger.info("%r", ever)
5
你应该使用extra这个参数:
views.py
import logging
class SampleClass():
def sample_func(self):
logging.getLogger('info_logger').info('some text', extra={'className': self.__class__.__name__})
logger_settings.py
'format': '%(className)s | %(message)s ',
输出日志:
INFO | SampleClass | "some text"
34
如果你想用一种简单又符合Python风格的方法来让你的日志输出类名,可以直接使用一个日志类。
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()