1

I would like to inject the arguments of a method which fire an error level log into the log.

I looked at this question and I think the inspect library could be a good choice to get the arguments of the method: Getting method parameter names in python

import inspect

def add(x,y):
    frame = inspect.currentframe()
    try:
        print(frame.f_locals)
    finally:
        del frame
    return x+y

Running: add(4,5)
Returns: {'frame': , 'y': 5, 'x': 4}

Though ideally I would only like to call the above inspect code to add the info to the error level logs automatically and only when they are called somehow overwriting the error logs.

Community
  • 1
  • 1
swartchris8
  • 620
  • 1
  • 6
  • 24

1 Answers1

1

This is an interesting question. Basically you can:

The result looks like this:

from functools import wraps
import logging
import inspect

# save the old logging.error function
__logging_error = logging.error

@wraps(logging.error)
def error(msg, *args, **kwargs):
    __logging_error(msg, *args, **kwargs)
    caller = inspect.stack()[1]
    caller_frame = caller[0]
    __logging_error('args: %s' % caller_frame.f_locals)

# overwrite the default logging.error
logging.error = error

Now the code:

def add(x, y):
    logging.error('this is an error')
    return x + y

add(4, 5)

outputs:

ERROR:root:this is an error
ERROR:root:args: {'y': 5, 'x': 4}
Community
  • 1
  • 1
enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
  • Thanks for the answer, your code is throwing a RecursionError but stepping back in the stack is a simple solution for my problem. – swartchris8 Nov 30 '16 at 14:03
  • @chrisvlll: this is curious, it doesn't throw anything to me. Try the whole script here: https://gist.github.com/enricobacis/83ca7bf163b27e95eb28288e0756f8cc – enrico.bacis Nov 30 '16 at 14:06
  • Apologies I ran it multiple times in ipython and due to the monkey patch it threw a RecursionError – swartchris8 Nov 30 '16 at 14:15