mytoolkit/mymanager.py
changeset 75 39f777341db4
parent 74 d4306261ddfb
child 77 2cfef775f518
--- a/mytoolkit/mymanager.py	Thu Mar 07 15:42:47 2013 +0100
+++ b/mytoolkit/mymanager.py	Thu Mar 07 18:26:52 2013 +0100
@@ -73,6 +73,7 @@
 
 
 log_sql = logging.getLogger("mymanager_sql")
+log_sql.addHandler(logging.NullHandler())
 
 
 class MyManagerError(Exception):
@@ -108,13 +109,13 @@
         try:
             return super(Cursor, self).execute(query, args)
         finally:
-            log_sql.debug(self._executed.decode('utf8'))
+            self._log_query(query, args)
 
     def callproc(self, procname, args=None):
         try:
             return super(Cursor, self).callproc(procname, args)
         finally:
-            log_sql.debug(self._executed.decode('utf8'))
+            self._log_query(query, args)
 
     def row_dict(self, row, lstrip=None):
         adjustname = lambda a: a
@@ -132,6 +133,24 @@
         rows = super(Cursor, self).fetchall()
         return [self.row_dict(row, lstrip) for row in rows]
 
+    def mogrify(self, query, args):
+        """Get query with substituted args as it will be send to server."""
+        if isinstance(query, bytes):
+            query = query.decode()
+        if args is not None:
+            db = self._get_db()
+            query = query % db.literal(args)
+        return query
+
+    def _log_query(self, query, args):
+        name = self.connection.name if hasattr(self.connection, 'name') else '-'
+        query = self._executed or self.mogrify(query, args)
+        if isinstance(query, bytes):
+            db = self._get_db()
+            charset = db.character_set_name()
+            query = query.decode(charset)
+        log_sql.info('[%s] %s' % (name, query))
+
 
 class MyManager: