在我的代码中,记录器以某种方式打印了两次事件,但常规print
显示了正确的事件数量。
select 1,2
select 1,2
2013-04-19 18:37:30,618:4561354752 - SQLLogger - DEBUG - select 1,2
2013-04-19 18:37:30,618:4561354752 - SQLLogger - DEBUG - select 1,2
2013-04-19 18:37:30,618:4565561344 - SQLLogger - DEBUG - select 1,2
2013-04-19 18:37:30,618:4565561344 - SQLLogger - DEBUG - select 1,2
我不清楚为什么在多线程情况下多次发布相同的消息。
import logging
from threading import Thread
class SQLEngine(object):
def __init__(self, DB_PATH):
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s:%(thread)d - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
self.logger = logging.getLogger('SQLLogger')
self.logger.setLevel(logging.DEBUG)
self.logger.addHandler(ch)
def execute(self,SQL,):
self.logger.debug(SQL)
print SQL
class DBWorker(Thread):
def __init__(self, name):
Thread.__init__(self)
self.name = name
def run(self):
db = SQLEngine('')
db.execute('select 1,2')
if __name__ == '__main__':
DBWorker('thread 1').start()
DBWorker('thread 2').start()