0

I want to have different formats per log level, i.e.:

logformat_info = "info ..."

logformat_warning = "warning ..."

My code so far (The logger is in a function because I pass it around between files):

def log(level='info'):
"""
    My logger function.
    :param level:
    :return:
"""
    log_colors = {
        "DEBUG": "white",
        "INFO": "green",
        "WARNING": "yellow",
        "ERROR": "red",
        "CRITICAL": "bold_red",
    }

    if level == 'info':
        LOG_LEVEL = logging.INFO
    elif level == 'debug':
        LOG_LEVEL = logging.DEBUG
    LOGFORMAT = "%(log_color)s%(log_color)s%(message)s%(reset)s"
    logging.root.setLevel(LOG_LEVEL)
    formatter = ColoredFormatter(LOGFORMAT, log_colors=log_colors)
    stream = logging.StreamHandler()
    stream.setLevel(LOG_LEVEL)
    stream.setFormatter(formatter)
    log_ = logging.getLogger('pythonConfig')
    log_.setLevel(LOG_LEVEL)
    log_.addHandler(stream)
    return log_

Thanks!

yonatan
  • 113
  • 9
  • 1
    possibly a duplicate of: [https://stackoverflow.com/questions/1343227/can-pythons-logging-format-be-modified-depending-on-the-message-log-level](https://stackoverflow.com/questions/1343227/can-pythons-logging-format-be-modified-depending-on-the-message-log-level) – Shlomo Gottlieb Feb 06 '22 at 09:29
  • 1
    See that specific and detailled answer https://stackoverflow.com/a/8349076/7212686 – azro Feb 06 '22 at 09:38
  • 1
    The duplicate is for Python 2. The accepted answer has a link to the Python 3 solution, which is https://stackoverflow.com/questions/14844970/modifying-logging-message-format-based-on-message-logging-level-in-python3 . That is likely a better duplicate. – 9769953 Feb 06 '22 at 12:51

0 Answers0