如何记录func_name和文件名

时间:2019-03-19 10:11:47

标签: python logging

我打包了一个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使用参数dc_path:/ disks输入。 我期望的是“星期二,2019年3月19日05:41:15 DEBUG file1 is_path_valid #strong_number使用参数dc_path输入/ disks”

我应该怎么办?

3 个答案:

答案 0 :(得分:0)

您最终可以使用traceback模块:

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)
  

注意:您不必每次调用debug()方法时都调用basicConfig方法,只需在记录器实例化时调用即可。在此处查看有关登录的最佳做法的更多信息:https://realpython.com/python-logging/

答案 1 :(得分:0)

根据logging Python official module部分中的LogRecord attributes,并获得预期的日志输出:

  

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

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

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

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

答案 2 :(得分:0)

已解决此问题,无需编写自己的记录器类。

相关问题