Reputation: 10400
I have a multithreading client-server software and it's a bit hard to debug when 10 client is connected. I have a few questions regarding the tracing.
Upvotes: 2
Views: 367
Reputation: 7343
import logging
import time
import pymongo
import hashlib
import random
DEBUG_MODE = True
class logger(object):
def __new__(cls, *args, **kwargs):
if DEBUG_MODE:
return object.__new__(cls, *args, **kwargs)
else:
return args[0]
def __init__(self, foo):
self.foo = foo
logging.basicConfig(filename='exceptions.log', format='%(levelname)s %(asctime)s: %(message)s')
self.log = logging.getLogger(__name__)
def __call__(self, *args, **kwargs):
def _log():
try:
t = time.time()
func_hash = self._make_hash(t)
col = self._make_db_connection()
log_record = {'func_name':self.foo.__name__, 'start_time':t, 'func_hash':func_hash}
col.insert(log_record)
res = self.foo(*args, **kwargs)
log_record = {'func_name':self.foo.__name__, 'exc_time':round(time.time() - t,4), 'end_time':time.time(),'func_hash':func_hash}
col.insert(log_record)
return res
except Exception as e:
self.log.error(e)
return _log()
def _make_db_connection(self):
connection = pymongo.Connection()
db = connection.logger
collection = db.log
return collection
def _make_hash(self, t):
m = hashlib.md5()
m.update(str(t)+str(random.randrange(1,10)))
return m.hexdigest()
Its use mongo as storage but you can write any backend. Just wrap function which you need and follow the log.
Upvotes: 2