ToolBase: add -d parameter, which triggers debug mode (print SQL queries).
authorRadek Brich <radek.brich@devl.cz>
Fri, 09 Sep 2011 11:56:37 +0200
changeset 13 16dc5dec9c36
parent 12 203be9022b46
child 14 a900bc629ecc
ToolBase: add -d parameter, which triggers debug mode (print SQL queries).
pgtoolkit/coloredformatter.py
pgtoolkit/toolbase.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/pgtoolkit/coloredformatter.py	Fri Sep 09 11:56:37 2011 +0200
@@ -0,0 +1,25 @@
+import logging
+
+from pgtoolkit import highlight
+
+
+class ColoredFormatter(logging.Formatter):
+    def __init__(self, fmt, datefmt):
+        logging.Formatter.__init__(self, fmt, datefmt)
+
+    def format(self, record):
+        color = ()
+        if record.levelno == 21:
+            color = (2, None)
+        if record.levelno == logging.ERROR and not record.exc_info is None:
+            color = (11, 1)
+        if color:
+            origmsg = record.msg
+            f,b = color
+            record.msg = highlight(1, f, b) + record.msg + highlight(0)
+            res = logging.Formatter.format(self, record)
+            record.msg = origmsg
+        else:
+            res = logging.Formatter.format(self, record)
+        return res
+
--- a/pgtoolkit/toolbase.py	Tue Sep 06 17:55:15 2011 +0200
+++ b/pgtoolkit/toolbase.py	Fri Sep 09 11:56:37 2011 +0200
@@ -1,11 +1,16 @@
 import argparse
+import logging
 
 from pgtoolkit import pgmanager, config
+from pgtoolkit.coloredformatter import ColoredFormatter
+from pgtoolkit.highlight import highlight
 
 
 class ToolBase:
     def __init__(self, name, desc):
         self.parser = argparse.ArgumentParser(description=desc)
+        self.parser.add_argument('-d', dest='debug', action='store_true',
+            help='Debug mode - print database queries.')
         
         self.config = config.ConfigParser()
         self.config.add_argument('databases', type=dict)
@@ -17,6 +22,14 @@
     def init(self):
         self.config.load('pgtoolkit.conf')
         self.args = self.parser.parse_args()
+        if self.args.debug:
+            handler = logging.StreamHandler()
+            format = ColoredFormatter(
+                highlight(1,7,0)+'%(asctime)s %(levelname)-5s'+highlight(0)+' %(message)s', '%H:%M:%S')
+            handler.setFormatter(format)
+            handler.setLevel(logging.DEBUG)
+            logger = logging.getLogger('pgmanager')
+            logger.addHandler(handler)
 
     def buildconn(self, name, targetname):
         with self.pgm.cursor('meta') as curs: