By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,621 Members | 1,077 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,621 IT Pros & Developers. It's quick & easy.

redirecting stdout to mysql table

P: n/a
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.

Nov 18 '08 #1
Share this Question
Share on Google+
1 Reply


P: n/a

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?

--
Skip Montanaro - sk**@pobox.com - http://smontanaro.dyndns.org/
Nov 18 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.