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

[((787, 838), 'logging.Formatter', 'logging.Formatter', ([], {'fmt': '"""%(levelname)s: %(message)s"""'}), "(fmt='%(levelname)s: %(message)s')\n", (804, 838), False, 'import logging\n'), ((1413, 1436), 'logging.getLogger', 'logging.getLogger', (['name'], {}), '(name)\n', (1430, 1436), False, 'import logging\n'), ((933, 941), 'platform.system', 'system', ([], {}), '()\n', (939, 941), False, 'from platform import system\n'), ((433, 448), 'tqdm.tqdm.write', 'tqdm.write', (['msg'], {}), '(msg)\n', (443, 448), False, 'from tqdm import tqdm\n'), ((413, 419), 'multiprocessing.Lock', 'Lock', ([], {}), '()\n', (417, 419), False, 'from multiprocessing import Lock\n'), ((1039, 1074), 'logging.getLevelName', 'logging.getLevelName', (['logging.ERROR'], {}), '(logging.ERROR)\n', (1059, 1074), False, 'import logging\n'), ((1148, 1185), 'logging.getLevelName', 'logging.getLevelName', (['logging.WARNING'], {}), '(logging.WARNING)\n', (1168, 1185), False, 'import logging\n'), ((1256, 1290), 'logging.getLevelName', 'logging.getLevelName', (['logging.INFO'], {}), '(logging.INFO)\n', (1276, 1290), False, 'import logging\n'), ((1362, 1397), 'logging.getLevelName', 'logging.getLevelName', (['logging.DEBUG'], {}), '(logging.DEBUG)\n', (1382, 1397), False, 'import logging\n')]