log: Make the log_exception support a per instance logger.
[matthijs/projects/backupninja.git] / src / lib / backupninja / log.py
index 9fa85b8b92dc13494db8e40e840abbe9126c6bfb..6f25f7db006dd0fda8990d4f667778c5f74a4c04 100644 (file)
@@ -32,5 +32,44 @@ def setup_logging(options):
     options are the parsed commandline options.
     """
     # We use the default options for now
-    logging.basicConfig()
+    level = logging.INFO
+    if(options.debug):
+        level = logging.DEBUG
+    logging.basicConfig(level=level)
     log.debug("Initialized logging configuration")
+
+def log_exception(log=None, msg="%s"):
+    """
+    This is a decorator that catches an exception, logs the exception
+    and a backtrace and then swallows it.  The exception is logged using
+    the "error" level for the message, and "debug" for the backtrace.
+
+    log is the Logger instance to log to. If this is not present, the
+    decorated function should be a method of an object that contains a
+    "log" attribute that contains a Logger instance.
+
+    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:
+                # Find out which logger to use. We create a new variabel
+                # logger here, since it seems to be impossible to assign
+                # the log variable from the log_exception scope.
+                if log is None:
+                    # No log is passed. Get the self argument (args[0]) and
+                    # get is "log" attribute.
+                    logger = args[0].log
+                else:
+                    # Use the passed log
+                    logger = log
+
+                logger.error(msg, e)
+                import traceback
+                logger.debug(traceback.format_exc())
+        return inner
+    return decorator