0

I wrote a decorator to log any exception a function might throw.

import logging def log_exception(func): def func_new(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: logging.error(str(e)) raise e return func_new 

It is used like this:

@log_exception def divide(a, b): return a/b 

For example, divide(1, 0) would log 'division by zero'.

My question is whether there's a builtin or more robust way to achieve the same thing. Maybe in the logging or contextlib modules?

9
  • 2
    What is wrong with your decorator that you want to replace it? Commented Mar 23, 2022 at 15:20
  • 1
    @ScottHunter Would you recommend to implement sum in Python over using the builtin sum? I'm asking whether I reimplemented a feature I'm not aware of. Commented Mar 23, 2022 at 15:22
  • Probably a good question to ask before you write your own solution. Commented Mar 23, 2022 at 15:25
  • Does this answer your question? Using python's logging module to log all exceptions and errors Commented Mar 23, 2022 at 15:26
  • 1
    "Maybe in the logging or contextlib modules?" Well, did you try reading the documentation for those modules? Or the logging module cookbook? Commented Mar 23, 2022 at 15:27

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.