Mokus
Mokus

Reputation: 10400

How can I trace a multi-thread software?

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.

  1. How can I trace a only a certain file or class in the software?
  2. Is there a possibility to have a log with a timestamp and the function name, without any other information and separated by threads?
  3. Is there a graphical trace generator?

Upvotes: 2

Views: 367

Answers (1)

Denis
Denis

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

Related Questions