mirror of
https://github.com/freedombox/FreedomBox.git
synced 2026-01-21 07:55:00 +00:00
logging: Implement colors for console messages
Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
parent
bc55edd186
commit
6afbd0d9fc
@ -27,6 +27,53 @@ import cherrypy
|
||||
from . import cfg
|
||||
|
||||
|
||||
class ColoredFormatter(logging.Formatter):
|
||||
"""Print parts of log message in color."""
|
||||
codes = {
|
||||
'black': 30,
|
||||
'red': 31,
|
||||
'green': 32,
|
||||
'yellow': 33,
|
||||
'blue': 34,
|
||||
'magenta': 35,
|
||||
'cyan': 36,
|
||||
'white': 37,
|
||||
'bright_black': 90,
|
||||
'bright_red': 91,
|
||||
'bright_green': 92,
|
||||
'bright_yellow': 93,
|
||||
'bright_blue': 94,
|
||||
'bright_magenta': 95,
|
||||
'bright_cyan': 96,
|
||||
'bright_white': 97
|
||||
}
|
||||
|
||||
level_colors = {
|
||||
'DEBUG': 'bright_black',
|
||||
'INFO': 'bright_white',
|
||||
'WARNING': 'bright_yellow',
|
||||
'ERROR': 'red',
|
||||
'CRITICAL': 'bright_red'
|
||||
}
|
||||
|
||||
def wrap_color(self, string, color=None):
|
||||
"""Return a string wrapped in terminal escape codes for coloring."""
|
||||
if not color:
|
||||
return string
|
||||
|
||||
return '\x1b[{}m'.format(self.codes[color]) + string + '\x1b[0m'
|
||||
|
||||
def format(self, record):
|
||||
"""Format a record into a string"""
|
||||
record_name = '{:<20}'.format(record.name)
|
||||
record.colored_name = self.wrap_color(record_name, 'bright_blue')
|
||||
|
||||
level_color = self.level_colors.get(record.levelname, None)
|
||||
level_name = '{:>8}'.format(record.levelname)
|
||||
record.colored_levelname = self.wrap_color(level_name, level_color)
|
||||
return super().format(record)
|
||||
|
||||
|
||||
def init():
|
||||
"""Setup the logging framework."""
|
||||
# Remove default handlers and let the log message propagate to root logger.
|
||||
@ -59,15 +106,16 @@ def get_configuration():
|
||||
'version': 1,
|
||||
'disable_existing_loggers': False,
|
||||
'formatters': {
|
||||
'default': {
|
||||
'format':
|
||||
'%(name)-14s %(levelname)-8s %(message)s',
|
||||
'color': {
|
||||
'()': 'plinth.log.ColoredFormatter',
|
||||
'format': '{colored_levelname} {colored_name} {message}',
|
||||
'style': '{'
|
||||
}
|
||||
},
|
||||
'handlers': {
|
||||
'console': {
|
||||
'class': 'logging.StreamHandler',
|
||||
'formatter': 'default'
|
||||
'formatter': 'color'
|
||||
}
|
||||
},
|
||||
'root': {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user