Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add Colors to Logging Python3
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import logging as log
from copy import copy
if not sys.platform.startswith("win") and sys.stderr.isatty():
def add_color_emit_ansi(fn):
"""Add methods we need to the class."""
def new(*args):
"""Method overload."""
if len(args) == 2:
new_args = (args[0], copy(args[1]))
else:
new_args = (args[0], copy(args[1]), args[2:])
if hasattr(args[0], 'baseFilename'):
return fn(*args)
levelno = new_args[1].levelno
if levelno >= 50:
color = '\x1b[31;5;7m\n ' # blinking red with black
elif levelno >= 40:
color = '\x1b[31m' # red
elif levelno >= 30:
color = '\x1b[33m' # yellow
elif levelno >= 20:
color = '\x1b[32m' # green
elif levelno >= 10:
color = '\x1b[35m' # pink
else:
color = '\x1b[0m' # normal
try:
new_args[1].msg = color + str(new_args[1].msg) + ' \x1b[0m'
except Exception as reason:
print(reason) # Do not use log here.
return fn(*new_args)
return new
# all non-Windows platforms support ANSI Colors so we use them
log.StreamHandler.emit = add_color_emit_ansi(log.StreamHandler.emit)
# optional: for testing
log.warning(42)
log.error(42)
log.critical(42)
log.info(42)
log.debug(42)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.