[chirp_devel] [PATCH 01/12] Fix chirp.logger module (#2347)

Zach Welch
Fri Feb 27 02:24:38 PST 2015


# HG changeset patch
# User Zach Welch <zach at mandolincreekfarm.com>
# Fake Node ID 0f651b4f02250339fc9ace7fd87075058f64cc21

Fix chirp.logger module (#2347)

This patch addresses some issues with the chirp.logger module in order
to use it in chirpc and chirpw.  It prints the version string when
logging at DEBUG level.

In addition, it embraces and extends the "debug.log" support that was
present in chirpw, ensuring all log messages and output end up in that
file when running on Win32 or MacOS hosts.  It also allows that feature
to be tested on Linux by setting CHIRP_DEBUG_LOG in the environment.

diff --git a/chirp/logger.py b/chirp/logger.py
index 4cf8fa2..eb29e6f 100644
--- a/chirp/logger.py
+++ b/chirp/logger.py
@@ -56,6 +56,9 @@ log_level_names = {"critical": logging.CRITICAL,
 
 
 class Logger(object):
+
+    log_format = '[%(asctime)s] %(name)s - %(levelname)s: %(message)s'
+
     def __init__(self):
         # create root logger
         self.logger = logging.getLogger()
@@ -67,20 +70,35 @@ class Logger(object):
         # It can be a number or a name; otherwise, level is set to 'debug'
         # in order to maintain backward compatibility.
         CHIRP_DEBUG = os.getenv("CHIRP_DEBUG")
-        level = logging.WARNING
+        self.early_level = logging.WARNING
         if CHIRP_DEBUG:
             try:
-                level = int(CHIRP_DEBUG)
+                self.early_level = int(CHIRP_DEBUG)
             except ValueError:
                 try:
-                    level = log_level_names[CHIRP_DEBUG]
+                    self.early_level = log_level_names[CHIRP_DEBUG]
                 except KeyError:
-                    level = logging.DEBUG
-
-        self.console = logging.StreamHandler()
-        self.console.setLevel(level)
-        format_str = '%(levelname)s: %(message)s'
-        self.console.setFormatter(logging.Formatter(format_str))
+                    self.early_level = logging.DEBUG
+
+        # If we're on Win32 or MacOS, we don't use the console; instead,
+        # we create 'debug.log', redirect all output there, and set the
+        # console logging handler level to DEBUG.  To test this on Linux,
+        # set CHIRP_DEBUG_LOG in the environment.
+        console_stream = None
+        console_format = '%(levelname)s: %(message)s'
+        if hasattr(sys, "frozen") or not os.isatty(0) \
+                or os.getenv("CHIRP_DEBUG_LOG"):
+            p = platform.get_platform()
+            log = file(p.config_file("debug.log"), "w", 0)
+            sys.stdout = log
+            sys.stderr = log
+            console_stream = log
+            console_format = self.log_format
+            self.early_level = logging.DEBUG
+
+        self.console = logging.StreamHandler(console_stream)
+        self.console.setLevel(self.early_level)
+        self.console.setFormatter(logging.Formatter(console_format))
         self.logger.addHandler(self.console)
 
         # Set CHIRP_LOG in environment to the name of log file.
@@ -94,31 +112,33 @@ class Logger(object):
             else:
                 self.set_log_level(logging.DEBUG)
 
+        if self.early_level <= logging.DEBUG:
+            self.LOG.debug(version_string())
+
     def create_log_file(self, name):
         if self.logfile is None:
             self.logname = name
-            lf = file(name, "w")
-            print >>lf, version_string()
-            lf.close()
+            # always truncate the log file
+            with file(name, "w") as fh:
+                pass
             self.logfile = logging.FileHandler(name)
-            format_str = '[%(created)s] %(name)s - %(levelname)s: %(message)s'
+            format_str = self.log_format
             self.logfile.setFormatter(logging.Formatter(format_str))
             self.logger.addHandler(self.logfile)
-
         else:
             self.logger.error("already logging to " + self.logname)
 
     def set_verbosity(self, level):
+        self.LOG.debug("verbosity=%d", level)
         if level > logging.CRITICAL:
             level = logging.CRITICAL
         self.console.setLevel(level)
-        self.LOG.debug("verbosity=%d", level)
 
     def set_log_level(self, level):
+        self.LOG.debug("log level=%d", level)
         if level > logging.CRITICAL:
             level = logging.CRITICAL
         self.logfile.setLevel(level)
-        self.LOG.debug("log level=%d", level)
 
     def set_log_level_by_name(self, level):
         self.set_log_level(log_level_names[level])
@@ -153,3 +173,6 @@ def handle_options(options):
             logger.set_log_level(level)
         except ValueError:
             logger.set_log_level_by_name(options.log_level)
+
+    if logger.early_level > logging.DEBUG:
+        logger.LOG.debug(version_string())
diff --git a/chirpc b/chirpc
index 6a25e50..16c7006 100755
--- a/chirpc
+++ b/chirpc
@@ -19,10 +19,14 @@
 import serial
 import sys
 import argparse
+import logging
 
+from chirp import logger
 from chirp import *
 from chirp import chirp_common, errors, idrp, directory, util
 
+LOG = logging.getLogger("chirpc")
+
 def fail_unsupported():
     print "Operation not supported by selected radio"
     sys.exit(1)
@@ -62,6 +66,7 @@ class DTCSPolarityAction(argparse.Action):
 
 if __name__ == "__main__":
 	parser = argparse.ArgumentParser()
+	logger.add_version_argument(parser)
 	parser.add_argument("-s", "--serial", dest="serial",
 			  default="mmap",
 			  help="Serial port (default: mmap)")
@@ -151,8 +156,10 @@ if __name__ == "__main__":
 			  action="store_true",
 			  default=False,
 			  help="Upload memory map to radio")
+        logger.add_arguments(parser)
         parser.add_argument("args", metavar="arg", nargs='*',
                             help="Some commands require additional arguments")
+
 	if len(sys.argv) <= 1:
 		parser.print_help()
 		sys.exit(0)
@@ -160,6 +167,8 @@ if __name__ == "__main__":
 	options = parser.parse_args()
         args = options.args
 
+        logger.handle_options(options)
+
         if options.list_radios:
             print "Supported Radios:\n\t", "\n\t".join(sorted(RADIOS.keys()))
             sys.exit(0)
diff --git a/chirpw b/chirpw
index a3a316c..67c9ee0 100755
--- a/chirpw
+++ b/chirpw
@@ -17,8 +17,9 @@
 
 import os
 
+from chirp import logger
 from chirp import elib_intl
-from chirp import platform, CHIRP_VERSION
+from chirp import platform
 from chirpui import config
 
 # Hack to setup environment
@@ -30,20 +31,6 @@ import locale
 import gettext
 import argparse
 
-p = platform.get_platform()
-if hasattr(sys, "frozen"):
-    log = file(p.config_file("debug.log"), "w", 0)
-    sys.stderr = log
-    sys.stdout = log
-elif not os.isatty(0):
-    log = file(p.config_file("debug.log"), "w", 0)
-    sys.stdout = log
-    sys.stderr = log
-
-print "CHIRP %s on %s (Python %s)" % (CHIRP_VERSION,
-                                      platform.get_platform().os_version_string(),
-                                      sys.version.split()[0])
-
 execpath = platform.get_platform().executable_path()
 localepath = os.path.abspath(os.path.join(execpath, "locale"))
 if not os.path.exists(localepath):
@@ -127,10 +114,14 @@ from chirpui import mainapp, config
 
 parser = argparse.ArgumentParser()
 parser.add_argument("files", metavar="file", nargs='*', help="File to open")
+logger.add_version_argument(parser)
 parser.add_argument("--profile", action="store_true",
                     help="Enable profiling")
+logger.add_arguments(parser)
 args = parser.parse_args()
 
+logger.handle_options(args)
+
 a = mainapp.ChirpMain()
 
 for i in args.files:




More information about the chirp_devel mailing list