import io
import logging
import sys
import traceback


def getExceptionTrackeback(ex: Exception):
    traceback_str = ""
    if ex is not None:
        try:
            with io.StringIO() as f:
                # traceback.print_tb(sys.exc_info()[2], file=f)
                traceback.print_exception(etype=type(
                    ex), value=ex, tb=ex.__traceback__,  file=f)
                traceback_str = f.getvalue()
        except Exception as exx:
            print(exx)
    return traceback_str


def loggerAddFileHandler(logger: logging.Logger, log_file: str,
                         level: int = logging.WARN,
                         format: str = '"%(asctime)s - %(message)s"'):
    handler = logging.FileHandler(log_file)
    handler.setLevel(level)

    formatter = logging.Formatter(format)
    handler.setFormatter(formatter)

    logger.addHandler(handler)


def initLogging(log_level=logging.INFO, format=None):
    """ Initialize logging framework

    """

    # name is the logger name,
    # thread is thread id
    DEFAULT_LOG_FORMAT = '%(asctime)s, %(name)s, %(thread)d' + \
        ', %(funcName)s, %(levelname)s: %(message)s'
    _format = format or DEFAULT_LOG_FORMAT

    # set the default logging configuration.

    # The basicConfig is used only once -
    # when the FIRST log message is generated
    logging.basicConfig(format=_format, level=log_level)

    # create a named logger for this module
    logger = logging.getLogger(__name__)
    logger.log(logging.INFO, "Initialized logging Framework.")
