[or-cvs] r24013: {arm} Providing an option to dump arm debug logs. (in arm/trunk/src: . util)

Damian Johnson atagar1 at gmail.com
Sat Jan 1 06:59:34 UTC 2011


Author: atagar
Date: 2011-01-01 06:59:34 +0000 (Sat, 01 Jan 2011)
New Revision: 24013

Modified:
   arm/trunk/src/starter.py
   arm/trunk/src/util/log.py
Log:
Providing an option to dump arm debug logs.



Modified: arm/trunk/src/starter.py
===================================================================
--- arm/trunk/src/starter.py	2011-01-01 05:56:25 UTC (rev 24012)
+++ arm/trunk/src/starter.py	2011-01-01 06:59:34 UTC (rev 24013)
@@ -27,6 +27,7 @@
 import TorCtl.TorCtl
 import TorCtl.TorUtil
 
+LOG_DUMP_PATH = os.path.expanduser("~/.arm/log")
 DEFAULT_CONFIG = os.path.expanduser("~/.arm/armrc")
 CONFIG = {"startup.controlPassword": None,
           "startup.interface.ipAddress": "127.0.0.1",
@@ -42,14 +43,15 @@
           "log.configDescriptions.persistance.saveSuccess": util.log.INFO,
           "log.configDescriptions.persistance.saveFailed": util.log.NOTICE}
 
-OPT = "i:c:be:vh"
-OPT_EXPANDED = ["interface=", "config=", "blind", "event=", "version", "help"]
+OPT = "i:c:dbe:vh"
+OPT_EXPANDED = ["interface=", "config=", "debug", "blind", "event=", "version", "help"]
 HELP_MSG = """Usage arm [OPTION]
 Terminal status monitor for Tor relays.
 
   -i, --interface [ADDRESS:]PORT  change control interface from %s:%i
   -c, --config CONFIG_PATH        loaded configuration options, CONFIG_PATH
                                     defaults to: %s
+  -d, --debug                     writes all arm logs to %s
   -b, --blind                     disable connection lookups
   -e, --event EVENT_FLAGS         event types in message log  (default: %s)
 %s
@@ -59,7 +61,7 @@
 Example:
 arm -b -i 1643          hide connection data, attaching to control port 1643
 arm -e we -c /tmp/cfg   use this configuration file with 'WARN'/'ERR' events
-""" % (CONFIG["startup.interface.ipAddress"], CONFIG["startup.interface.port"], DEFAULT_CONFIG, CONFIG["startup.events"], interface.logPanel.EVENT_LISTING)
+""" % (CONFIG["startup.interface.ipAddress"], CONFIG["startup.interface.port"], DEFAULT_CONFIG, LOG_DUMP_PATH, CONFIG["startup.events"], interface.logPanel.EVENT_LISTING)
 
 # filename used for cached tor config descriptions
 CONFIG_DESC_FILENAME = "torConfigDescriptions.txt"
@@ -161,6 +163,7 @@
 if __name__ == '__main__':
   startTime = time.time()
   param = dict([(key, None) for key in CONFIG.keys()])
+  isDebugMode = False
   configPath = DEFAULT_CONFIG # path used for customized configuration
   
   # parses user input, noting any issues
@@ -189,6 +192,7 @@
       param["startup.interface.ipAddress"] = controlAddr
       param["startup.interface.port"] = controlPort
     elif opt in ("-c", "--config"): configPath = arg  # sets path of user's config
+    elif opt in ("-d", "--debug"): isDebugMode = True # dumps all logs
     elif opt in ("-b", "--blind"):
       param["startup.blindModeEnabled"] = True        # prevents connection lookups
     elif opt in ("-e", "--event"):
@@ -200,6 +204,19 @@
       print HELP_MSG
       sys.exit()
   
+  if isDebugMode:
+    try:
+      util.log.setDumpFile(LOG_DUMP_PATH)
+      
+      currentTime = time.localtime()
+      timeLabel = time.strftime("%H:%M:%S %m/%d/%Y (%Z)", currentTime)
+      initMsg = "Arm %s Debug Dump, %s" % (version.VERSION, timeLabel)
+      
+      util.log.DUMP_FILE.write("%s\n%s\n" % (initMsg, "-" * len(initMsg)))
+      util.log.DUMP_FILE.flush()
+    except IOError, exc:
+      print "Unable to write to debug log file: %s" % util.sysTools.getFileErrorMsg(exc)
+  
   config = util.conf.getConfig("arm")
   
   # attempts to fetch attributes for parsing tor's logs, configuration, etc

Modified: arm/trunk/src/util/log.py
===================================================================
--- arm/trunk/src/util/log.py	2011-01-01 05:56:25 UTC (rev 24012)
+++ arm/trunk/src/util/log.py	2011-01-01 06:59:34 UTC (rev 24013)
@@ -6,6 +6,7 @@
 safe.
 """
 
+import os
 import time
 from sys import maxint
 from threading import RLock
@@ -27,6 +28,8 @@
 CONFIG = {"cache.armLog.size": 1000,
           "cache.armLog.trimSize": 200}
 
+DUMP_FILE = None
+
 def loadConfig(config):
   config.update(CONFIG, {
     "cache.armLog.size": 10,
@@ -34,6 +37,24 @@
   
   CONFIG["cache.armLog.trimSize"] = min(CONFIG["cache.armLog.trimSize"], CONFIG["cache.armLog.size"] / 2)
 
+def setDumpFile(logPath):
+  """
+  Logs all future logged events to the given path. This raises an IOError if
+  the file fails to be opened. If the file already exists then this overwrites
+  it.
+  
+  Arguments:
+    logPath - path where to persist logs
+  """
+  
+  global DUMP_FILE
+  
+  # make sure that the parent directory exists
+  baseDir = os.path.dirname(logPath)
+  if not os.path.exists(baseDir): os.makedirs(baseDir)
+  
+  DUMP_FILE = open(logPath, "w")
+
 def strToRunlevel(runlevelStr):
   """
   Converts runlevel strings ("DEBUG", "INFO", "NOTICE", etc) to their
@@ -75,6 +96,7 @@
     eventTime - unix time at which the event occurred, current time if undefined
   """
   
+  global DUMP_FILE
   if not level: return
   if eventTime == None: eventTime = time.time()
   
@@ -101,6 +123,18 @@
     toDelete = len(eventBacklog) - CONFIG["cache.armLog.size"]
     if toDelete >= 0: del eventBacklog[: toDelete + CONFIG["cache.armLog.trimSize"]]
     
+    # persists the event if a debug file's been set
+    if DUMP_FILE:
+      try:
+        entryTime = time.localtime(eventTime)
+        timeLabel = "%i/%i/%i %02i:%02i:%02i" % (entryTime[1], entryTime[2], entryTime[0], entryTime[3], entryTime[4], entryTime[5])
+        logEntry = "%s [%s] %s\n" % (timeLabel, runlevelToStr(level), msg)
+        DUMP_FILE.write(logEntry)
+        DUMP_FILE.flush()
+      except IOError, exc:
+        DUMP_FILE = None
+        log(ERR, "Failed to write to the debug file - %s" % exc)
+    
     # notifies listeners
     for callback in _listeners[level]:
       callback(RUNLEVEL_STR[level], msg, eventTime)



More information about the tor-commits mailing list