【问题标题】:how to logging func_name and filename如何记录 func_name 和文件名
【发布时间】:2019-03-19 10:11:46
【问题描述】:

我打包了一个类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”。 我期望的是“Tue, 19 Mar 2019 05:41:15 DEBUG file1 is_path_valid #line_number Entering with parameter dc_path: /disks”

我该怎么办?

【问题讨论】:

  • 为什么要创建自己的记录器类,至少在这个例子中,它没有提供任何超出正常记录模块的额外内容。使用后者,您为包或模块设置记录器(不是默认的根记录器,即不使用logging.basicConfig),在模块内部,您使用logger = logging.getLogger(__name__)
  • 您的自定义记录器仅公开其中一个日志级别,并在每次debugged 时重新配置日志记录。我建议查看the docs 并坚持使用上述更传统的模式。
  • 旁白:不要使用% 将您的日志字符串与要记录的变量连接起来。使用logger.debug('Entering with parameter dc_path: %s', (dc_path))(逗号而不是第二个% 符号)。这节省了一些幕后时间,因为格式化在使用日志级别时完成。
  • 我只是在这个logger类中粘贴了部分代码(比如error level print logging.exception)。我需要在几个模块中记录数据,所以我认为最好创建自己的记录器类。

标签: python logging


【解决方案1】:

您最终可以使用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/

【讨论】:

  • 谢谢。但是如果它太重而无法获得轨道堆栈?我想找到一个简单的方法。
  • 为什么会“太重而无法获取堆栈跟踪”?
  • 我觉得 traceback.extract_stack()[-1] 应该很慢,而且我不需要获取堆栈跟踪,只想使用日志记录来记录信息。
【解决方案2】:

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

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'

请注意从 funcNamefilename 的变化,因为您要查找的是文件名,而且您将获得:路径名的文件名部分。

【讨论】:

  • 不,这不是根本原因,我也尝试了文件名,但仍然是 logger.py 没有在日志文件中调用模块文件名。
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 2021-01-29
    • 2014-11-18
    • 2013-04-12
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多