I have a utility method which does some logging.
I would like to see the calling method name in the logs, and not the name of the utility method.
For testing I tried this (later I want to get "bar" from the caller via the inspect module).
def helper(...): logger.info('foo', extra=dict(funcName='bar'))
But this does not work:
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"
Here is the output (if I don't try to pass in "extra"):
2017-01-30 15:00:24 loghelper.helper
I would like to see the caller:
2017-01-30 15:00:24 calling_module.calling_method
How could this be done?
The method-name and other data gets outputted via a logging Formater:
logging.Formatter('%(asctime)s %(name)s.%(funcName)s +%(lineno)s: %(levelname)-8s [%(process)d] %(message)s', '%Y-%m-%d %H:%M:%S')
You can add an intermediate method which will further call the
def autolog(message): "Automatically log the current function details." import inspect, 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. logging.debug("%s: %s in %s:%i" % ( message, func.co_name, func.co_filename, func.co_firstlineno ))