File size: 2,222 Bytes
19c8b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import logging
from platform import system
from tqdm import tqdm
import sys

loggers = {}


# https://stackoverflow.com/questions/38543506/
class TqdmLoggingHandler(logging.StreamHandler):
    def __init__(self):
        super().__init__(sys.stderr)

    def emit(self, record):
        try:
            msg = self.format(record)
            set_mp_lock()
            tqdm.write(msg, file=sys.stderr)
            self.flush()
        except (KeyboardInterrupt, SystemExit):
            raise
        except Exception:
            self.handleError(record)

def set_mp_lock():
    try:
        from multiprocessing import Lock
        tqdm.set_lock(Lock())
    except (ImportError, OSError):
        # Some python environments do not support multiprocessing
        # See: https://github.com/slhck/ffmpeg-normalize/issues/156
        pass

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 = logging.StreamHandler()
    handler = TqdmLoggingHandler()
    handler.setFormatter(formatter)

    # \033[1;30m - black
    # \033[1;31m - red
    # \033[1;32m - green
    # \033[1;33m - yellow
    # \033[1;34m - blue
    # \033[1;35m - magenta
    # \033[1;36m - cyan
    # \033[1;37m - white

    if system() not in ["Windows", "cli"]:
        logging.addLevelName(
            logging.ERROR, f"{logging.getLevelName(logging.ERROR)}"
        )
        logging.addLevelName(
            logging.WARNING,
            f"{logging.getLevelName(logging.WARNING)}",
        )
        logging.addLevelName(
            logging.INFO, f"{logging.getLevelName(logging.INFO)}"
        )
        logging.addLevelName(
            logging.DEBUG, f"{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