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

标签 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)()

最佳答案

这原来是一个 x/y 问题。根据 this answerlogging 似乎具有我需要的所有功能.

通过在格式语句中使用属性 %(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()

关于python - 当前方法和类名进入日志记录;这些方法在功能上是否等效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53516968/

相关文章:

python - 用 python 中的枕头分离/重新定位/翻译图像中的形状

python - Python 3.X 中同名的类型和函数?

python - 如何在不调用函数的情况下获取函数的属性

python - 类型错误 : 'DataFrame' object is not callable error when using seaborn pairplot ?

python - 如何从两个点数组创建 Shapely LineString

python - Python 中的 zip(*) 功能

python - 如何根据scrapy中本周的日期获取上周作为开始日期和结束日期

python - 打印以逗号分隔的列表,不带尾随逗号

python - 浮点运算 : Possible unsafe reliance on specific comparison?

python - 删除列表中字符串的所有扩展名