为了账号安全,请及时绑定邮箱和手机立即绑定

如何记录 func_name 和文件名

如何记录 func_name 和文件名

萧十郎 2021-12-09 15:39:56
我打包了一个类Logger。class Logger:    def __init__(self, logfile):        self.log_file = logfile    def debug(self, message):        logging.basicConfig(level=logging.DEBUG,                            format='%(asctime)-15s %(levelname)s %(module)s %(funcName)s %(lineno)d %(message)s',                            datefmt='%a, %d %b %Y %H:%M:%S',                            filename=self.log_file,                            filemode='w')        logging.debug(message)然后我在主函数中创建记录器实例。然后我在另一个类文件 file1 中使用了这个记录器。  def is_path_valid(self, dc_path):      self.logger.debug('Entering with parameter dc_path: %s' %(dc_path))但是这个写在日志文件中的日志是“Tue, 19 Mar 2019 05:41:15 DEBUG logger debug 14 Entering with parameter dc_path: /disks”。我期望的是“2019 年 3 月 19 日星期二 05:41:15 DEBUG file1 is_path_valid #line_number 输入参数 dc_path:/disks”我应该怎么做?
查看完整描述

2 回答

?
沧海一幻觉

TA贡献1824条经验 获得超5个赞

您最终可以使用回溯模块:


import traceback


def your_method(param):

    print(traceback.format_stack())  # the stacktrace formatted

    print(traceback.extract_stack())  # the stacktrace as a list, you could only get the last item


your_method(1)

您可以通过以下方式转换您的 debug() 方法来实现这一点:


def debug(self, message):

    logging.debug('%s - %s', traceback.extract_stack()[-1], message)

注意:您不需要basicConfig每次调用 debug() 方法时都调用该方法,只需在您的记录器实例化时调用它即可;在此处查看有关日志记录良好做法的更多信息:https : //realpython.com/python-logging/


查看完整回答
反对 回复 2021-12-09
?
POPMUISE

TA贡献1765条经验 获得超5个赞

根据LogRecord 属性部分中的日志记录 Python 官方模块,并为了获得预期的日志输出:

2019 年 3 月 19 日,星期二 05:41:15 DEBUG file1 is_path_valid #line_number 输入参数 dc_path: /disks

您的格式日志记录属性应如下所示:

'%(asctime)-15s %(levelname)s %(module)s %(filename)s %(lineno)d %(message)s'

请注意从funcName到的更改,filename因为您要查找的是文件名,并且您还将获得:路径名的文件名部分。


查看完整回答
反对 回复 2021-12-09
  • 2 回答
  • 0 关注
  • 169 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信