Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ANSI colored Python logging
import logging
from termcolor import colored
class ColorLog(object):
colormap = dict(
debug=dict(color='grey', attrs=['bold']),
info=dict(color='white'),
warn=dict(color='yellow', attrs=['bold']),
warning=dict(color='yellow', attrs=['bold']),
error=dict(color='red'),
critical=dict(color='red', attrs=['bold']),
)
def __init__(self, logger):
self._log = logger
def __getattr__(self, name):
if name in ['debug', 'info', 'warn', 'warning', 'error', 'critical']:
return lambda s, *args: getattr(self._log, name)(
colored(s, **self.colormap[name]), *args)
return getattr(self._log, name)
log = ColorLog(logging.getLogger(__name__))
if __name__ == '__main__':
log.setLevel(logging.DEBUG)
stdout = logging.StreamHandler()
stdout.setLevel(logging.DEBUG)
log.addHandler(stdout)
log.debug("booooring . . .")
log.info("pleasing anecdote")
log.warn("awkward utterance")
log.error("drunken rudeness")
@pmcao

This comment has been minimized.

Copy link

commented Apr 23, 2013

This is excellent! However it does not print current function name in logging! Perhaps because of the lambda keyword in line 21?

@brainsik

This comment has been minimized.

Copy link
Owner Author

commented May 17, 2013

@pmcao This is just using the default logging format. You can have it display whatever you want. See the Formatter docs:

http://docs.python.org/2/library/logging.html#logging.Formatter

@jaredjenkins

This comment has been minimized.

Copy link

commented Aug 5, 2013

Thanks for throwing this together.

@elsa-heer

This comment has been minimized.

Copy link

commented Feb 27, 2017

I really like your approach. Do you know how to avoid the ANSI escape codes in the log files if I add a file handler?

@KurtJacobson

This comment has been minimized.

Copy link

commented Jun 28, 2017

@elsa-heer I know it has been a long time since you commented on this, but I also needed to avoid the the ANSI escape sequences in the log file. Here is the solution I came up with: https://gist.github.com/KurtJacobson/c87425ad8db411c73c6359933e5db9f9

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.