Skip to content

Instantly share code, notes, and snippets.

@legend80s
Last active August 13, 2016 13:34
Show Gist options
  • Save legend80s/97a2bc6eb1fe733f8d8f9a4ca0914296 to your computer and use it in GitHub Desktop.
Save legend80s/97a2bc6eb1fe733f8d8f9a4ca0914296 to your computer and use it in GitHub Desktop.
class ColorPrinter:
"""
print message to terminal with colored header
"""
def __init__(self, header=''):
self.__header = header
self.__levels = {
'log': '\033[0m', # terminal color header
'info': '\033[1;32;40m', # green header
'warn': '\033[1;33;40m', # yellow header
'error': '\033[1;31;40m', # red header
}
def setHeader(self, header=''):
self.__header = header
def __format(self, message, level='log'):
header = self.__levels.get(level, self.__levels['log']) + self.__header + self.__levels['log'] if self.__header else ''
body = ' ' + message if message else ''
return header + body
# `info` print the message with terminal color header
def log(self, message='', *others):
print self.__format(' '.join((message,) + others), 'log')
return self
# `info` print the message with green header
def info(self, message='', *others):
print self.__format(' '.join((message,) + others), 'info')
return self
# `warn` print the message with yellow header
def warn(self, message='', *others):
print self.__format(' '.join((message,) + others), 'warn')
return self
# `error` print the message with red header
def error(self, message='', *others):
print self.__format(' '.join((message,) + others), 'error')
return self
'''usage
printer = ColorPrinter('Legend:')
printer.log('hello world', 'and', 'hello kitty')
printer.info('hello world', 'and', 'hello kitty')
printer.warn('hello world', 'and', 'hello kitty')
printer.error('hello world', 'and', 'hello kitty')
print
printer.setHeader('[LEGEND]:')
printer.log('hello world', 'and', 'hello kitty')
printer.info('hello world', 'and', 'hello kitty')
printer.warn('hello world', 'and', 'hello kitty')
printer.error('hello world', 'and', 'hello kitty')
print
printer.setHeader('[legend]:')
printer.log('hello world', 'and', 'hello kitty') \
.info('hello world', 'and', 'hello kitty') \
.warn('hello world', 'and', 'hello kitty') \
.error('hello world', 'and', 'hello kitty')
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment