redirecting stdout to mysql table

N

n00b

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.
 
S

skip

n00b> def openDb(self):
n00b> try:
n00b> self.db = MySQLdb.connect(host = self.db_host,
n00b> user = self.db_uname,
n00b> passwd = self.db_passwd,
n00b> db = self.db_name,
n00b> )
n00b>
n00b> self.cur = self.db.cursor()
n00b> return self.db, self.cur
n00b> except Exception, e:
n00b> sys.stdout = sys.__stdout__
n00b> sys.stderr = sys.__stderr__
n00b> print e[0], e[1]
n00b> sys.exit(1)
...
n00b> def write(self, string):
n00b> s = string.strip('\n')
n00b> if not s=='':
n00b> self.openDb()
n00b> self.cur.execute(self.sql, (s))
n00b> self.db.commit()
n00b> self.closeDb()

You don't really want to open a new database connection for every write call
do you?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top