import logging
from platform import system
from tqdm import tqdm
from multiprocessing import Lock

loggers = {}


# https://stackoverflow.com/questions/38543506/
class TqdmLoggingHandler(logging.Handler):
    def __init__(self, level=logging.NOTSET):
        super(TqdmLoggingHandler, self).__init__(level)

    def emit(self, record):
        try:
            msg = self.format(record)
            tqdm.set_lock(Lock())
            tqdm.write(msg)
            self.flush()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)

def setup_custom_logger(name):
    """
    Create a logger with a certain name and level
    """
    global loggers

    if loggers.get(name):
        return loggers.get(name)

    formatter = logging.Formatter(
        fmt='%(levelname)s: %(message)s'
    )

    handler = TqdmLoggingHandler()
    handler.setFormatter(formatter)

    if system() not in ['Windows', 'cli']:
        logging.addLevelName(logging.ERROR, "\033[1;31m%s\033[1;0m" % logging.getLevelName(logging.ERROR))
        logging.addLevelName(logging.WARNING, "\033[1;33m%s\033[1;0m" % logging.getLevelName(logging.WARNING))
        logging.addLevelName(logging.INFO, "\033[1;34m%s\033[1;0m" % logging.getLevelName(logging.INFO))
        logging.addLevelName(logging.DEBUG, "\033[1;35m%s\033[1;0m" % logging.getLevelName(logging.DEBUG))

    logger = logging.getLogger(name)
    logger.setLevel(logging.WARNING)

    # if (logger.hasHandlers()):
    #     logger.handlers.clear()
    if logger.handlers:
        logger.handlers = []
    logger.addHandler(handler)
    loggers.update(dict(name=logger))

    return logger

[((34, 16, 36, 5), 'logging.Formatter', 'logging.Formatter', (), '', False, 'import logging\n'), ((47, 13, 47, 36), 'logging.getLogger', 'logging.getLogger', ({(47, 31, 47, 35): 'name'}, {}), '(name)', False, 'import logging\n'), ((41, 7, 41, 15), 'platform.system', 'system', ({}, {}), '()', False, 'from platform import system\n'), ((18, 12, 18, 27), 'tqdm.tqdm.write', 'tqdm.write', ({(18, 23, 18, 26): 'msg'}, {}), '(msg)', False, 'from tqdm import tqdm\n'), ((17, 26, 17, 32), 'multiprocessing.Lock', 'Lock', ({}, {}), '()', False, 'from multiprocessing import Lock\n'), ((42, 70, 42, 105), 'logging.getLevelName', 'logging.getLevelName', ({(42, 91, 42, 104): 'logging.ERROR'}, {}), '(logging.ERROR)', False, 'import logging\n'), ((43, 72, 43, 109), 'logging.getLevelName', 'logging.getLevelName', ({(43, 93, 43, 108): 'logging.WARNING'}, {}), '(logging.WARNING)', False, 'import logging\n'), ((44, 69, 44, 103), 'logging.getLevelName', 'logging.getLevelName', ({(44, 90, 44, 102): 'logging.INFO'}, {}), '(logging.INFO)', False, 'import logging\n'), ((45, 70, 45, 105), 'logging.getLevelName', 'logging.getLevelName', ({(45, 91, 45, 104): 'logging.DEBUG'}, {}), '(logging.DEBUG)', False, 'import logging\n')]