Source code for MPF.commonHelpers.logger

"""
Logger template
"""

import logging
import atexit

from .. import globalStyle as gst

# create logger
logger = logging.getLogger("MPF") # name should be given, otherwise we are configuring the root logger
memeLogger = logging.getLogger("meme") # we also configure this one

# configure logging if no handlers exist (neither for MPF nor the root logger)
if (len(logger.handlers) < 1
    and len(logging.getLogger().handlers) < 1):

    logger.setLevel(logging.INFO)

    # create console handler and set level to debug
    ch = logging.StreamHandler()

    # create formatter
    formatter = logging.Formatter('<%(levelname)s> %(name)s %(funcName)s: %(message)s')

    # add formatter to ch
    ch.setFormatter(formatter)
    logger.addHandler(ch)

    # also configure meme logger if no handlers exist (or only NullHandler)
    if (len(memeLogger.handlers) < 1
        or (len(memeLogger.handlers) == 1 and  not memeLogger.handlers[0])):
        memeLogger.addHandler(ch)
        memeLogger.setLevel(logging.INFO)

    # based on stackoverflow post - quick and dirty hack for colors ;)
    # -> Maybe switch to a solution where this is only configured for this particular logger
    BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = [30+_i for _i in range(8)]
    RESET_SEQ = "\033[0m"
    COLOR_SEQ = "\033[1;%dm"
    BOLD_SEQ = "\033[1m"
    colorMapping = {
        logging.INFO : GREEN,
        logging.DEBUG : BLUE,
        logging.WARNING: YELLOW,
        logging.ERROR: RED,
    }
    for loglevel, color in colorMapping.items():
        logging.addLevelName(loglevel, "{COLOR_SEQ}{LEVELNAME}{RESET_SEQ}".format(COLOR_SEQ=COLOR_SEQ % color,
                                                                                  LEVELNAME=logging.getLevelName(loglevel),
                                                                                  RESET_SEQ=RESET_SEQ))

[docs]def done(): if gst.thankYou: import sys if hasattr(sys, "last_value"): logger.info("- Ruined.") else: logger.info("Thanks MPF - Thmpf.")
if gst.thankYou: atexit.register(done)