fix logging code
authorStefan Huber <shuber2@gmx.at>
Tue, 15 May 2012 08:08:26 +0000 (10:08 +0200)
committerStefan Huber <shuber2@gmx.at>
Tue, 15 May 2012 08:08:26 +0000 (10:08 +0200)
shbackup

index da28afecb1c8532307a7c795b29bf63be63ee2a1..41658696b6097a9272b3e49a0f7e291ec515e004 100755 (executable)
--- a/shbackup
+++ b/shbackup
@@ -255,9 +255,9 @@ class BackupManager:
     def backupFileSet(self, fileset, targetdir, since=None):
         """Create an archive for given fileset at given target directory."""
 
-        logger = logging.getLogger('backup')
+        logfile = logging.getLogger('backuplog')
+        logfile.info("Running file set: " + fileset.name)
 
-        logger.info("Running file set: " + fileset.name)
         tarpath = "/bin/tar"
         fsfn = os.path.join(targetdir, fileset.name) + "." + self.conf.format
 
@@ -270,7 +270,7 @@ class BackupManager:
             taropts += ["--exclude", pat]
 
         tarargs = [tarpath] + taropts + ["-f", fsfn] + fileset.dirs
-        logger.debug("tar call: " + " ".join(tarargs))
+        logfile.debug("tar call: " + " ".join(tarargs))
         tarp = subprocess.Popen( tarargs, bufsize=-1, \
                 stdout=subprocess.PIPE, stderr=subprocess.PIPE )
 
@@ -287,9 +287,9 @@ class BackupManager:
         rett = tarp.wait()
         if rett != 0:
             for l in tarp.stderr.readlines():
-                logger.error( l.decode().strip().rstrip() )
+                logfile.error( l.decode().strip().rstrip() )
             sys.stderr.write( tarp.stderr.read().decode() )
-            logger.error(tarpath + " returned with exit status " + str(rett) + ".")
+            logfile.error(tarpath + " returned with exit status " + str(rett) + ".")
 
 
     def backup(self, epoch=None, mode=None):
@@ -345,17 +345,19 @@ class BackupManager:
         os.mkdir( targetdir )
 
 
-        logger = logging.getLogger('backup')
-        ch = logging.FileHandler( os.path.join(targetdir, "log") )
-        ch.setLevel(logging.INFO)
-        logger.addHandler(ch)
-        logger.info("Started: " + now.ctime())
+        # Add file logger
+        logfile = logging.getLogger("backuplog")
+        fil = logging.FileHandler( os.path.join(targetdir, "log") )
+        fil.setLevel(logging.DEBUG)
+        logfile.addHandler(fil)
+
+        logfile.info("Started: " + now.ctime())
 
         # Backup all file sets
         for s in self.conf.sets:
             self.backupFileSet(s, targetdir, since)
 
-        logger.info("Stopped: " + datetime.datetime.now().ctime())
+        logfile.info("Stopped: " + datetime.datetime.now().ctime())
 
         # Rename backup directory to final name
         os.rename( targetdir, os.path.join(basedir, dirname) )
@@ -416,7 +418,7 @@ class BackupManager:
                 shutil.rmtree(os.path.join(basedir, d))
 
     def ask_user_yesno(self, question):
-        if logging.getLogger().isEnabledFor(logging.INFO):
+        if LogConf.con.level <= logging.INFO:
             return input(question)
         else:
             return "y"
@@ -449,9 +451,29 @@ def printUsage():
     print("  -V, --version              print version info")
 
 
+
+class LogConf:
+    """Encapsulates logging configuration"""
+
+    con = logging.StreamHandler(sys.stderr)
+
+    @classmethod
+    def setup(cls):
+        """Setup logging system"""
+        conlog = logging.getLogger()
+        conlog.setLevel(logging.DEBUG)
+
+        cls.con.setLevel(logging.WARNING)
+        conlog.addHandler(cls.con)
+
+        fillog = logging.getLogger("backuplog")
+        fillog.setLevel(logging.DEBUG)
+
+
 if __name__ == "__main__":
 
-    logging.basicConfig(format='%(message)s')
+    LogConf.setup()
+
     conffn = "/etc/shbackup.conf"
     cmd = "list"
     mode = None
@@ -475,7 +497,7 @@ if __name__ == "__main__":
             exit(0)
 
         elif opt in ["-v", "--verbose"]:
-            logging.getLogger().setLevel(logging.INFO)
+            LogConf.con.setLevel(logging.INFO)
 
         elif opt in ["--verbosity"]:
             i += 1
@@ -483,7 +505,7 @@ if __name__ == "__main__":
             numlevel = getattr(logging, level.upper(), None)
             if not isinstance(numlevel, int):
                 raise ValueError('Invalid verbosity level: %s' % level)
-            logging.getLogger().setLevel(numlevel)
+            LogConf.con.setLevel(numlevel)
 
         elif opt in ["-m", "--mode"]:
             i += 1