log: Add log_exception decorator.
authorMatthijs Kooijman <matthijs@stdin.nl>
Sat, 7 Aug 2010 18:46:22 +0000 (20:46 +0200)
committerMatthijs Kooijman <matthijs@stdin.nl>
Sat, 7 Aug 2010 18:46:22 +0000 (20:46 +0200)
This decorator catches, logs and swallows exceptions thrown in the
decorated function.

src/lib/backupninja/log.py

index d9d4dfac876d943af79698b2747c096af39f6ddc..86a31813e50e5f723d1cec9df8fc787ba891b471 100644 (file)
@@ -37,3 +37,22 @@ def setup_logging(options):
         level = logging.DEBUG
     logging.basicConfig(level=level)
     log.debug("Initialized logging configuration")
         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