在日志记录中覆盖“funcName”

时间:2017-01-30 14:02:52

标签: python logging

我有一个实用程序方法可以进行一些记录。

我想在日志中看到调用方法名称,而不是实用程序方法的名称。

为了测试我尝试了这个(后来我想通过inspect模块从调用者那里获得“bar”)。

def helper(...):
    logger.info('foo', extra=dict(funcName='bar'))

但这不起作用:

  File "/usr/lib/python2.7/logging/__init__.py", line 1167, in info
    self._log(INFO, msg, args, **kwargs)
  File "/usr/lib/python2.7/logging/__init__.py", line 1285, in _log
    record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra)
  File "/usr/lib/python2.7/logging/__init__.py", line 1263, in makeRecord
    raise KeyError("Attempt to overwrite %r in LogRecord" % key)
KeyError: "Attempt to overwrite 'funcName' in LogRecord"

这是输出(如果我不尝试传递“额外”):

2017-01-30 15:00:24 loghelper.helper

我想看看来电者:

2017-01-30 15:00:24 calling_module.calling_method

怎么可以这样做?

更新

方法名称和其他数据通过日志记录Formater输出:

logging.Formatter('%(asctime)s %(name)s.%(funcName)s +%(lineno)s: %(levelname)-8s [%(process)d] %(message)s',
                                   '%Y-%m-%d %H:%M:%S')

1 个答案:

答案 0 :(得分:1)

您可以添加一个中间方法,该方法将进一步调用logging方法。

def autolog(message, extra):
    "Automatically log the current function details."
    import inspect
    import logging
    # Get the previous frame in the stack, otherwise it would
    # be this function!!!
    func = inspect.currentframe().f_back.f_code
    # Dump the message + the name of this function to the log.
    funcName = extra.get('funcName') or func.co_name

    logging.debug("%s: %s in %s:%i" % (
        message,
        funcName,
        func.co_filename,
        func.co_firstlineno
    ))
相关问题