From: Matthijs Kooijman Date: Sat, 7 Aug 2010 18:46:22 +0000 (+0200) Subject: log: Add log_exception decorator. X-Git-Url: https://git.stderr.nl/gitweb?a=commitdiff_plain;h=83ac2051e6b8583650fa9ce295afe8c61526b692;p=matthijs%2Fprojects%2Fbackupninja.git log: Add log_exception decorator. This decorator catches, logs and swallows exceptions thrown in the decorated function. --- diff --git a/src/lib/backupninja/log.py b/src/lib/backupninja/log.py index d9d4dfa..86a3181 100644 --- a/src/lib/backupninja/log.py +++ b/src/lib/backupninja/log.py @@ -37,3 +37,22 @@ def setup_logging(options): level = logging.DEBUG logging.basicConfig(level=level) log.debug("Initialized logging configuration") + +def log_exception(log, msg="%s"): + """ + This is a decorator that catches an exception, logs the exception + and a backtrace and then swallows it. log is the Logging instance to + log to (using the "error" level for the message, and "debug" for the + backtrace), msg is the message to log (which must contain a %s into + which the exception message is interpolated). + """ + def decorator(f): + def inner(*args, **kwargs): + try: + f(*args, **kwargs) + except Exception, e: + log.error(msg, e) + import traceback + log.debug(traceback.format_exc()) + return inner + return decorator