changeset 77:e5e7b6e9bd44

Implement debug levels in the main code.
author Matti Hamalainen <ccr@tnsp.org>
date Wed, 13 Jul 2016 12:33:12 +0300
parents a63cc3633adb
children 784cac877428
files multimerge.py
diffstat 1 files changed, 34 insertions(+), 27 deletions(-) [+]
line wrap: on
line diff
--- a/multimerge.py	Wed Jul 13 11:50:25 2016 +0300
+++ b/multimerge.py	Wed Jul 13 12:33:12 2016 +0300
@@ -40,6 +40,10 @@
 gcm_log_levels = ["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"]
 
 
+def gcm_get_log_level():
+    return gcm_log_levels.index(cfg.logging_level)
+
+
 ## Wrapper for print() that does not break when redirecting stdin/out
 ## because of piped output not having a defined encoding. We default
 ## to UTF-8 encoding in output here.
@@ -71,9 +75,12 @@
 
 
 ## Debug messages
-def gcm_debug(smsg):
-    if cfg.debug:
-        gcm_print(u"DBG: "+ smsg)
+def gcm_check_debug(level):
+    return cfg.debug and gcm_get_log_level() >= level
+
+def gcm_debug(level, smsg):
+    if gcm_check_debug(level):
+        gcm_print(u"DBG: {0}".format(smsg))
     else:
         gcm_msgbuf.append(u"DBG: {0}".format(smsg))
 
@@ -250,7 +257,7 @@
             if cfgparser.has_option(sect, name):
                 value = cfgparser.get(sect, name)
                 self.mset(name, value)
-                gcm_debug(u"{0} -> '{1}' == {2}".format(name, value, self.mget(name)))
+                gcm_debug(4, u"{0} -> '{1}' == {2}".format(name, value, self.mget(name)))
 
     def is_str(self, mvalue):
         return isinstance(mvalue, basestring)
@@ -366,7 +373,7 @@
 
 ## Read, parse and validate configuration file
 if len(sys.argv) > 1:
-    gcm_debug(u"Reading configuration from '{0}'.".format(sys.argv[1]))
+    gcm_debug(3, u"Reading configuration from '{0}'.".format(sys.argv[1]))
     try:
         cfgparser = ConfigParser.RawConfigParser()
         cfgparser.readfp(codecs.open(sys.argv[1], "r", "UTF-8"))
@@ -421,7 +428,7 @@
 
 
 ## Fetch complete calendar list
-gcm_debug(u"Fetching available calendars ..")
+gcm_debug(3, u"Fetching available calendars ..")
 calendars = []
 cal_token = None
 while True:
@@ -440,7 +447,7 @@
 if len(calendars) == 0:
     gcm_fatal(u"No calendars found?")
 
-gcm_debug(u"{0} calendars total found.".format(len(calendars)))
+gcm_debug(3, u"{0} calendars total found.".format(len(calendars)))
 
 
 ## Filter desired SOURCE calendars based on specified regexp
@@ -465,14 +472,14 @@
             calendar["gcm_id"] = mre.group(cfg.source_regmap[1])
             src_calendars.append(calendar)
 
-gcm_debug(u"{0} source calendars found.".format(len(src_calendars)))
+gcm_debug(3, u"{0} source calendars found.".format(len(src_calendars)))
 
 
 ## Check if we have destination calendar ID
 if not dst_calendar:
     gcm_fatal(u"Could not find target/destination calendar ID for '"+ cfg.dest_name +"'.")
 else:
-    gcm_debug(u"Target calendar '{0}' id {1}.".format(dst_calendar["summary"], dst_calendar["id"]))
+    gcm_debug(3, u"Target calendar '{0}' id {1}.".format(dst_calendar["summary"], dst_calendar["id"]))
 
 
 ## Fetch colors
@@ -483,10 +490,10 @@
 
 
 ## Now, we fetch and collect events
-gcm_debug(u"Fetching calendar events .. ")
+gcm_debug(3, u"Fetching calendar events .. ")
 src_events = []
 for calendar in src_calendars:
-    gcm_debug(u"- "+calendar["id"])
+    gcm_debug(4, u"- "+calendar["id"])
     try:
         result = service.events().list(
             timeZone="EEST",
@@ -500,12 +507,12 @@
 
     c_found = None
     if "colorId" in calendar and calendar["colorId"] in colors["calendar"]:
-        gcm_debug(u"Calendar color: {0}".format(colors["calendar"][calendar["colorId"]]))
+        gcm_debug(4, u"Calendar color: {0}".format(colors["calendar"][calendar["colorId"]]))
         c_found = gcm_find_nearest_color(colors["event"], colors["calendar"][calendar["colorId"]], 100)
         if c_found:
-            gcm_debug(u"Found nearest event color ID: {0}, {1}".format(c_found, colors["event"][c_found]))
+            gcm_debug(4, u"Found nearest event color ID: {0}, {1}".format(c_found, colors["event"][c_found]))
         else:
-            gcm_debug(u"No matching event color found!")
+            gcm_debug(4, u"No matching event color found!")
 
     # Add events, if any, to main list
     events = gcm_generate_ids(result.get("items", []), calendar["id"], "___")
@@ -515,12 +522,12 @@
                 event["colorId"] = c_found
             event["summary"] = u"[{1}] {0}".format(event["summary"], calendar["gcm_id"])
         src_events.extend(events)
-        if cfg.debug:
+        if gcm_check_debug(4):
             gcm_dump_events(events)
 
 
 ## Get current events
-gcm_debug(u"Fetching current target calendar events {0}".format(cfg.dest_id))
+gcm_debug(3, u"Fetching current target calendar events {0}".format(cfg.dest_id))
 result = service.events().list(
     calendarId=cfg.dest_id,
     singleEvents=True,
@@ -528,11 +535,11 @@
     ).execute()
 
 dst_events = gcm_generate_ids(result.get("items", []), "", "")
-gcm_debug(u"Found {0} event(s).".format(len(dst_events)))
+gcm_debug(3, u"Found {0} event(s).".format(len(dst_events)))
 
 
 ## Start merging events ..
-gcm_debug(u"Re-merging events to target calendar ..")
+gcm_debug(3, u"Re-merging events to target calendar ..")
 dst_ids = frozenset(map(lambda x: x["gcm_id"], dst_events))
 src_ids = frozenset(map(lambda x: x["gcm_id"], src_events))
 
@@ -540,11 +547,11 @@
     # Does the event exist already in the target?
     if event["gcm_id"] in dst_ids:
         # Check if event NEEDS updating .. aka compare data
-        gcm_debug(u"Event {0} : {1} exists, checking ..".format(event["id"], event["gcm_id"]))
+        gcm_debug(4, u"Event {0} : {1} exists, checking ..".format(event["id"], event["gcm_id"]))
         d_event = gcm_get_event_by_gcm_id(dst_events, event["gcm_id"])
         if not gcm_compare_events(event, d_event):
             # Seems we need to update
-            gcm_debug(u"Updating event {0} : {1}..".format(event["id"], event["gcm_id"]))
+            gcm_debug(4, u"Updating event {0} : {1}..".format(event["id"], event["gcm_id"]))
             try:
                 event.pop("sequence", None)
                 event.pop("id", None)
@@ -553,10 +560,10 @@
             except Exception as e:
                 gcm_fatal(u"Failed to update event {0}:\n\n{1}\n\nERROR: {2}\n".format(event["gcm_id"], event, str(e)))
         else:
-            gcm_debug(u"No need to update event {0} : {1}.".format(event["id"], event["gcm_id"]))
+            gcm_debug(4, u"No need to update event {0} : {1}.".format(event["id"], event["gcm_id"]))
     else:
         ## Event does not seem to exist. Insert new event.
-        gcm_debug(u"Inserting new event {0}".format(event["gcm_id"]))
+        gcm_debug(4, u"Inserting new event {0}".format(event["gcm_id"]))
         event.pop("id", None)
         event["iCalUID"] = event["gcm_id"]     # Replace Google generated ID with our own
         try:
@@ -566,11 +573,11 @@
 
 
 ## Remove "stale" events
-gcm_debug(u"Purging stale events ..")
+gcm_debug(3, u"Purging stale events ..")
 for event in dst_events:
-    gcm_debug(u"Checking event {0}".format(event["gcm_id"]))
+    gcm_debug(4, u"Checking event {0}".format(event["gcm_id"]))
     if not event["gcm_id"] in src_ids and event["status"] != u"cancelled":
-        gcm_debug(u"Deleting event {0}".format(event["gcm_id"]))
+        gcm_debug(4, u"Deleting event {0}".format(event["gcm_id"]))
         try:
             service.events().delete(calendarId=cfg.dest_id, eventId=event["id"]).execute()
         except Exception as e:
@@ -581,7 +588,7 @@
 ##
 t_time = time.localtime()
 t_str = time.strftime("%d.%m.%Y %H:%M", t_time)
-gcm_debug(u"Updating target calendar name timestamp {0}".format(t_str))
+gcm_debug(3, u"Updating target calendar name timestamp {0}".format(t_str))
 
 try:
     dst_calendar["summary"] = cfg.dest_name.format(t_str)
@@ -590,4 +597,4 @@
     gcm_fatal(u"Failed to update target calendar:\n{0}\n\nERROR: {1}\n".format(dst_calendar, str(e)))
 
 
-gcm_debug(u"Finished.")
+gcm_debug(3, u"Finished.")