redirecting stdout to mysql table

n00b pyn00b at gmail.com
Tue Nov 18 14:02:20 EST 2008


greetings,

i would like to redirect stdout/err to a mysql table and would like a)
some peer review and b) suggestions for hardening the approach for a
general purpose class. thank you very much.
import sys
import MySQLdb

class DBLogger(object):
    def __init__(self):
        self.db_name = 'odb'
        self.db_host = '127.0.0.1'
        self.db_table = 'sftp_manager_log'
        self.db_uname = 'roo'
        self.db_passwd = ''
        self.db_port = 3306
        self.db = None
        self.cur = None
        self.sql = 'INSERT INTO %s' %self.db_table + ' VALUES(null, NOW
(), %s)'


    def openDb(self):
        try:
            self.db = MySQLdb.connect(host = self.db_host,
                                        user = self.db_uname,
                                        passwd = self.db_passwd,
                                        db = self.db_name,
                                        )

            self.cur = self.db.cursor()
            return self.db, self.cur
        except Exception, e:
            sys.stdout = sys.__stdout__
            sys.stderr = sys.__stderr__
            print e[0], e[1]
            sys.exit(1)

    def closeDb(self):
       self.cur.close()
       self.db.close()

    def write(self, string):
        s = string.strip('\n')
        if not s=='':
            self.openDb()
            self.cur.execute(self.sql, (s))
            self.db.commit()
            self.closeDb()


dbl = DBLogger()
sys.stdout = dbl
sys.stderr = dbl

print 'a b c '
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__


thanks again for taking the time.




More information about the Python-list mailing list