From 83ac2051e6b8583650fa9ce295afe8c61526b692 Mon Sep 17 00:00:00 2001 From: Matthijs Kooijman Date: Sat, 7 Aug 2010 20:46:22 +0200 Subject: [PATCH] log: Add log_exception decorator. This decorator catches, logs and swallows exceptions thrown in the decorated function. --- src/lib/backupninja/log.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) 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 -- 2.30.2