【问题标题】:Arguments passed to create a LogRecord in python传递参数以在 python 中创建 LogRecord
【发布时间】:2019-12-13 20:09:52
【问题描述】:

python的logging module中的LogRecord有一个LogRecord定义为:

class LogRecord(object):
    """
    A LogRecord instance represents an event being logged.
    LogRecord instances are created every time something is logged. They
    contain all the information pertinent to the event being logged. The
    main information passed in is in msg and args, which are combined
    using str(msg) % args to create the message field of the record. The
    record also includes information such as when the record was created,
    the source line where the logging call was made, and any exception
    information to be logged.
    """
    def __init__(self, name, level, pathname, lineno,
                 msg, args, exc_info, func=None, sinfo=None, **kwargs):
        """
        Initialize a logging record with interesting information.
        """
        ct = time.time()
        self.name = name
        self.msg = msg
        # more stuff below

创建此LogRecord,例如每当有人执行logging 操作时,例如:

def my_func():
    logging.info('Hello %s', 'Person')
    return 1

在上面的logger调用中,变量可以推断为:

name = 'root' # using the root logger since calling `logging.`
level = 'INFO' # or, 20
msg = 'Hello %s'
args = ('Person',)

内省如何从我的logging 电话中收集其他项目?例如:

  • 路径名
  • 亚麻布
  • exc_info
  • 功能
  • sinfo # 这是什么?
  • kwargs # 这只是用户添加的 kwargs,还是其他?

例如,在您的回答中,您能否展示一个对函数调用进行自省以收集上述信息的示例?

【问题讨论】:

  • 调试器可以回答它
  • @jfs -- 你想举一个例子来说明如何做到这一点吗?

标签: python logging python-internals


【解决方案1】:

几乎所有这些都发生在Logger.findCaller。它检查当前帧以获取此信息。

实际上没有使用默认 LogRecord 构造函数的 kwargs 参数。用户提供的数据通过extra 传递。

【讨论】:

  • 所以它基本上提出了一个假的Exception 来从日志调用中获取所有堆栈信息?这很有趣。
  • 当 sys._getframe 不可用时会这样做。如果您对信息来自的对象的外观感兴趣,您应该查看回溯文档:docs.python.org/3/library/traceback.html
猜你喜欢
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 2016-02-08
  • 2012-10-19
  • 2022-07-22
  • 1970-01-01
  • 2019-01-14
相关资源
最近更新 更多