Python使用inspect库获取调用堆栈信息

由于logging库在云端系统的各种问题,需要自己实现一个日志器。通过inspect可以获取到当前函数的调用者所在行号、函数名等信息。也就是程序运行堆栈监视。

建议日志如下:

class getLogger():
    def debug(self, msg):
        if DEBUG:
            print('%s - DEBUG:%d - %s'%(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()),inspect.stack()[1][2], msg))
    def info(self, msg):
        print('%s - INFO:%d - %s'%(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), inspect.stack()[1][2], msg))
    def error(self, msg):
        print('%s - ERROR:%d - %s'%(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), inspect.stack()[1][2], msg))

由于时间关系没有深究,推测inspect.stack()[1][2]的两极索引分别对应栈偏移、变量项目。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值