Kaynağa Gözat

move setting up of the logger to the configuration module

Helmut Pozimski 6 yıl önce
ebeveyn
işleme
0f9d479ef8
2 değiştirilmiş dosya ile 49 ekleme ve 48 silme
  1. 28 1
      lib_stov/configuration.py
  2. 21 47
      stov

+ 28 - 1
lib_stov/configuration.py

@@ -23,6 +23,7 @@ stov, the configuration file is expected to be in json format and reside in
 import os
 import subprocess
 import json
+import logging
 
 from lib_stov import stov_exceptions
 
@@ -117,7 +118,8 @@ class Conf(object):
         else:
             process = subprocess.Popen(["which", "youtube-dl"],
                                        stdout=subprocess.PIPE)
-            self.values["youtube-dl"] = process.communicate()[0].strip().decode("utf-8")
+            self.values["youtube-dl"] = \
+                process.communicate()[0].strip().decode("utf-8")
             self.write_config()
 
     def read_old_config(self):
@@ -258,3 +260,28 @@ class Conf(object):
             raise stov_exceptions.ConfigurationMigrationFailed
         else:
             os.remove(str(os.environ['HOME']) + "/.stov/stov.config")
+
+    def configure_logging(self, verbose=False, quiet=False):
+        """
+        Sets up logging for stov and returns a logger object
+
+        :param verbose: whether to use verbose mode
+        :type verbose: bool
+        :param quiet: whether to use quiet mode
+        :type quiet: bool
+        :return: logger object
+        :rtype: logging.Logger
+        """
+        logger = logging.getLogger("stov")
+        # verbose takes precedence
+        if verbose:
+            logger.setLevel(logging.DEBUG)
+            self.outputlevel = "verbose"
+        elif quiet:
+            logger.setLevel(logging.ERROR)
+            self.outputlevel = "quiet"
+        else:
+            logger.setLevel(logging.INFO)
+        console_handler = logging.StreamHandler()
+        logger.addHandler(console_handler)
+        return logger

+ 21 - 47
stov

@@ -32,7 +32,6 @@ import smtplib
 import subprocess
 import signal
 import socket
-import logging
 from email.mime.multipart import MIMEMultipart
 from email.mime.text import MIMEText
 from optparse import OptionParser
@@ -43,13 +42,6 @@ from lib_stov import stov_exceptions
 from lib_stov import database
 
 
-# Setup the logger to log messages to stdout and stderr
-
-LOGGER = logging.getLogger("stov")
-LOGGER.setLevel(logging.DEBUG)
-CONSOLE_HANDLER = logging.StreamHandler()
-LOGGER.addHandler(CONSOLE_HANDLER)
-
 # Determine the path where the stov files are for localization
 
 LOCALE_PATH = os.path.join(sys.path[0] + "/locale")
@@ -168,24 +160,6 @@ if __name__ != "__main__":
           "please run it directly from command line")
     sys.exit(1)
 
-# Check which outputlevel is defined and save it to a temporary variable
-# accordingly. Output generated before this will be printed to stdout
-# regardless of the user defined setting
-
-
-if OPTIONS.verbose is True and OPTIONS.quiet is True:
-    print(_("--quiet and --verbose can't be defined at the same time, "
-            "exiting."), file=sys.stderr)
-    sys.exit(1)
-elif OPTIONS.verbose is True:
-    OUTPUT_LEVEL = "verbose"
-    LOGGER.setLevel(logging.DEBUG)
-elif OPTIONS.quiet is True:
-    OUTPUT_LEVEL = "quiet"
-    LOGGER.setLevel(logging.ERROR)
-else:
-    OUTPUT_LEVEL = "default"
-    LOGGER.setLevel(logging.INFO)
 
 # Create the lock file which is used to determine if another instance is
 # already running by chance, the program shouldn't be run in this case since
@@ -195,38 +169,42 @@ if os.access("/tmp/stov.lock", os.F_OK):
     try:
         LOCK_FILE = open("/tmp/stov.lock", "r")
     except IOError:
-        LOGGER.error(_("The lock file could not be opened, please check that "
-                       "it exists and is readable, quitting now"))
+        print(_("The lock file could not be opened, please check that "
+                "it exists and is readable, quitting now"),
+              file=sys.stderr)
         sys.exit(1)
     OLD_PID = LOCK_FILE.read().strip()
     if os.access("/proc/" + OLD_PID, os.F_OK):
-        LOGGER.error(_("The lock file already exists, probably another "
-                       "instance of this program is already running\n"
-                       "if you are sure this is not the case, delete it"
-                       " manually and try again!"))
+        print(_("The lock file already exists, probably another "
+                "instance of this program is already running\n"
+                "if you are sure this is not the case, delete it"
+                " manually and try again!"), file=sys.stderr)
         sys.exit(1)
     LOCK_FILE.close()
     if os.access("/proc/" + OLD_PID, os.F_OK) is not True:
         try:
             os.remove("/tmp/stov.lock")
         except os.error:
-            LOGGER.error(_("The old lock file could not be deleted!"))
+            print(_("The old lock file could not be deleted!"),
+                  file=sys.stderr)
 try:
     LOCK_FILE = open("/tmp/stov.lock", "w")
     LOCK_FILE.write(str(os.getpid()))
     LOCK_FILE.close()
 except IOError:
-    LOGGER.error(_("The lock file could not be created, please check that /tmp"
-                   " is writable and properly configured, quitting now."))
+    print(_("The lock file could not be created, please check that /tmp"
+            " is writable and properly configured, quitting now."),
+          file=sys.stderr)
     sys.exit(1)
 
 # Check if the configuration directory exists and is writeable. If it
 # doesnt, create it using the configuration class.
 
-if os.access(os.environ['HOME'] + "/.stov", os.F_OK & os.W_OK) is not True:
-    LOGGER.info(_("This seems to be the first time you run the programm, do "
-                  "you want to run the interactive assistant? (yes/no)"))
+if not os.access(os.environ['HOME'] + "/.stov", os.F_OK & os.W_OK):
+    print(_("This seems to be the first time you run the programm, do "
+            "you want to run the interactive assistant? (yes/no)"))
     CONF = configuration.Conf()
+    LOGGER = CONF.configure_logging(OPTIONS.verbose, OPTIONS.quiet)
     TEMP_INPUT = input()
     if TEMP_INPUT == "yes":
         CONF.assist()
@@ -250,6 +228,7 @@ if os.access(os.environ['HOME'] + "/.stov", os.F_OK & os.W_OK) is not True:
             LOGGER.error(error)
 else:
     CONF = configuration.Conf()
+    LOGGER = CONF.configure_logging(OPTIONS.verbose, OPTIONS.quiet)
     if os.access(str(os.environ['HOME']) + "/.stov/stov.config", os.F_OK):
         LOGGER.debug(_("Migrating configuration from plain text to json."))
         CONF.migrate_config()
@@ -316,11 +295,6 @@ except stov_exceptions.DBWriteAccessFailedException as error:
     LOGGER.error(error)
     sys.exit(1)
 
-# Check which outputlevel is defined and update the configuration object
-# accordingly.
-
-CONF.outputlevel = OUTPUT_LEVEL
-
 # youtube-dl is really a dependency but the program will run with limited
 # functionality without it so we need to check that here
 
@@ -408,8 +382,8 @@ if OPTIONS.add is True:
                 else:
                     LOGGER.debug(_("Video %s successfully inserted into "
                                    "database."), video.title)
-    LOGGER.info(_("New subscription ") + NEW_SUBSCRIPTION.get_title()
-                + _(" successfully added"))
+    LOGGER.info(_("New subscription ") + NEW_SUBSCRIPTION.get_title() +
+                _(" successfully added"))
 elif OPTIONS.list is True:
     LIST_OF_SUBSCRIPTIONS = DB.get_subscriptions(CONF)
     SUB_STATE = None
@@ -420,8 +394,8 @@ elif OPTIONS.list is True:
                 SUB_STATE = _("enabled")
             elif sub.disabled:
                 SUB_STATE = _("disabled")
-            LOGGER.info(str(sub.get_id()) + " " + sub.get_title()
-                        + " (%s)" % SUB_STATE)
+            LOGGER.info(str(sub.get_id()) + " " + sub.get_title() +
+                        " (%s)" % SUB_STATE)
     else:
         LOGGER.info(_("No subscriptions added yet, add one!"))
 elif OPTIONS.deleteid is not None: