当前方法和类名进入日志记录;这些方法在功能上是否等效?

时间:2018-11-28 10:12:52

标签: python python-3.x python-2.7

在下面基于先前答案的测试脚本中,所有技术都提供了将信息性消息返回到屏幕和日志文件的理想结果。

除了execution time似乎对于检查方法而言要慢得多,我看不出有任何方法可以在这些替代方法之间进行选择。一种或其他技术中是否存在任何隐患?我将在将来移动项目Python 3,以便最向前兼容的东西要好于现在最快的东西。

结果:

I am Bob, an instance of B, speaking from f1
I am Bob, an instance of B, speaking from f2
I am Bob, an instance of B, speaking from f3
I am Bob, an instance of B, speaking from f4
I am Bob, an instance of B, speaking from g
I am Bob, an instance of B, speaking from h

脚本:

class A(object):
    def __init__(self):
        self.cname = self.__class__.__name__
        logfmt     = "%(levelname)s - %(message)s"
        logging.basicConfig(filename="logme.log", level=logging.DEBUG, 
                            format=logfmt, filemode='w')
        self.logger = logging.getLogger()

class B(A):
    def __init__(self, name):
        self.name = name
        A.__init__(self)

    def whoami(self):
        return inspect.stack()[1][3]

    def whosdaddy(self):
        return inspect.stack()[2][3]

    def who_i(self, i=None):
        if i==None: i=1
        return inspect.stack()[i][3]

    def mee(self):
        return inspect.stack()[1][3]

    def f1(self):
        msg   = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, self.mee()))
        print msg
        self.logger.info(msg) 

    def f2(self):    # 2011 https://stackoverflow.com/a/5067654/3904031
        me  = inspect.stack()[0][3]
        msg   = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, me))
        print msg
        self.logger.info(msg) 

    def f3(self):    # 2015 https://stackoverflow.com/a/33159791/3904031
        msg   = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, self.whoami()))
        print msg
        self.logger.info(msg) 

    def f4(self):
        msg   = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, self.who_i(1)))
        print msg
        self.logger.info(msg) 

    def g(self):
        me  = sys._getframe().f_code.co_name    # 2013 https://stackoverflow.com/a/15725912/3904031
        msg   = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, me))
        print msg
        self.logger.info(msg) 

    def h(self):
        frame = inspect.currentframe()
        me    = inspect.getframeinfo(frame).function    # 2015 https://stackoverflow.com/a/33162432/3904031
        msg   = ('I am {}, an instance of {}, speaking from {}'.format(self.name, self.cname, me))
        print msg
        self.logger.info(msg) 

import sys, inspect, logging

b = B('Bob')

for x in ['f1', 'f2', 'f3', 'f4', 'g', 'h']:
    getattr(b, x)()

1 个答案:

答案 0 :(得分:1)

事实证明这是一个x / y问题。 this answer似乎logging具有我需要的所有功能。

通过在f​​ormat语句中使用属性%(funcName)s,以下脚本无需查看堆栈即可完成所有工作,包括回显控制台。

文档:https://docs.python.org/3/library/logging.html#logrecord-attributes

I am Bob, an instance of B, speaking from  i

来自:

class A(object):
    def __init__(self):

        self.cname = self.__class__.__name__

        logformat  = '%(message)s %(funcName)s '

        logging.basicConfig(filename="logme.log", level=logging.DEBUG, 
                            format=logformat, filemode='w')

        self.logger = logging.getLogger()

        console   = logging.StreamHandler()   # no more print statements, yay!
        formatter = logging.Formatter(logformat)
        console.setFormatter(formatter)

        console.setLevel(logging.DEBUG)

        logging.getLogger('').addHandler(console)

class B(A):
    def __init__(self, name):
        self.name = name
        A.__init__(self)

    def i(self):
        msg   = ('I am {x.name}, an instance of {x.cname}, speaking from '.format(x=self))
        self.logger.info(msg)

import sys, inspect, logging

b = B('Bob')

b.i()