How can I log a functions arguments in a reusable way in Python? -
i've found myself writing code several times:
def my_func(a, b, *args, **kwargs): saved_args = locals() # learned http://stackoverflow.com/a/3137022/2829764 local_var = "this other local var don't want log" try: a/b except exception e: logging.exception("oh no! args were: " + str(saved_args)) raise
running my_func(1, 0, "spam", "ham", my_kwarg="eggs")
gives output on stderr:
error:root:oh no! args were: {'a': 1, 'args': (u'spam', u'ham'), 'b': 0, 'kwargs': {'my_kwarg': u'eggs'}} traceback (most recent call last): file "/users/kuzzooroo/desktop/question.py", line 17, in my_func a/b zerodivisionerror: division 0
my question is, can write reusable don't have save locals() @ top of function? , can done in nice pythonic way?
edit: 1 more request in response @mtik00: ideally i'd way access saved_args or within my_func can other log uncaught exceptions (maybe want catch exception in my_func, log error, , keep going).
decorators looking for. here's example:
import logging functools import wraps def arg_logger(func): @wraps(func) def new_func(*args, **kwargs): saved_args = locals() try: return func(*args, **kwargs) except: logging.exception("oh no! args were: " + str(saved_args)) raise return new_func @arg_logger def func(arg1, arg2): return 1 / 0 if __name__ == '__main__': func(1, 2)
here, i'm using arg_logger() decorator. apply decorator function want have new behavior.
there's discussion decorators here.
Comments
Post a Comment