Python调用日志记录。获取基类名称

时间:2011-09-09 14:04:50

标签: python

我有一个Python源:

import inspect  
import logging  

logging.basicConfig(level=logging.DEBUG)  

class base_class:  
    def base_method(self):  
      logging.debug("  %s:%s() {" % (self.__class__.__name__, (inspect.stack()[0][3])))
      # . . .
      logging.debug("  } // %s:%s()" % (self.__class__.__name__, (inspect.stack()[0][3])))

class derived_class(base_class):
  def derived_method(self):
    logging.debug("%s:%s()." % (self.__class__.__name__, (inspect.stack()[0][3])))
    self.base_method()
    logging.debug("} // %s:%s()" % (self.__class__.__name__, (inspect.stack()[0][3])))

derived_class().derived_method()

打印:

DEBUG:root:derived_class:derived_method().
DEBUG:root:  derived_class:base_method() {
DEBUG:root:  } // derived_class:base_method()
DEBUG:root:} // derived_class:derived_method()

我想:

DEBUG:root:derived_class:derived_method().
DEBUG:root:  base_class:base_method() {
DEBUG:root:  } // base_class:base_method()
DEBUG:root:} // derived_class:derived_method()

这可能吗? 几个小时后我找不到答案。

1 个答案:

答案 0 :(得分:1)

为什么你这样做是可以讨论的,但我认为你最好的办法是手动指定类名

class base_class(object):  
    def base_method(self):  
      logging.debug("  %s:%s() {" % ( base_class.__name__, (inspect.stack()[0][3])))
      # . . .
      logging.debug("  } // %s:%s()" % (base_class.__name__, (inspect.stack()[0][3])))

class derived_class(base_class):
  def derived_method(self):

      logging.debug("%s:%s()." % ( derived_class.__name__, (inspect.stack()[0][3])))
      self.base_method()
      logging.debug("} // %s:%s()" % ( derived_class.__name__, (inspect.stack()[0][3])))