Skip to main content
 首页 » 编程设计

python之在日志记录中覆盖 "funcName"

2025年02月15日13jackei

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

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

为了测试我尝试了这个(后来我想通过检查模块从调用者那里得到“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" 

这是输出(如果我不尝试传入“extra”):

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

我想见来电者:

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

这是怎么做到的?

更新

方法名称和其他数据通过日志格式器输出:

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

请您参考如下方法:

您可以添加一个中间方法,该方法将进一步调用 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 
    ))