Merge "Provide reset_color key on log record"

This commit is contained in:
Zuul 2018-06-08 12:24:22 +00:00 committed by Gerrit Code Review
commit 4b4dabebab
2 changed files with 11 additions and 3 deletions

View File

@ -146,6 +146,12 @@ class OSJournalHandler(logging.Handler):
class ColorHandler(logging.StreamHandler):
"""Log handler that sets the 'color' key based on the level
To use, include a '%(color)s' entry in the logging_context_format_string
and a '%(reset_color)s' entry at the end of the format string so that the
color setting does not persist between log lines.
"""
LEVEL_COLORS = {
_TRACE: '\033[00;35m', # MAGENTA
logging.DEBUG: '\033[00;32m', # GREEN
@ -158,4 +164,5 @@ class ColorHandler(logging.StreamHandler):
def format(self, record):
record.color = self.LEVEL_COLORS[record.levelno]
record.reset_color = '\033[00m'
return logging.StreamHandler.format(self, record)

View File

@ -987,7 +987,8 @@ class FancyRecordTestCase(LogTestBase):
"[%(request_id)s]: "
"%(instance)s"
"%(resource)s"
"%(message)s",
"%(message)s"
"%(reset_color)s",
logging_default_format_string="%(missing)s: %(message)s")
self.colorlog = log.getLogger()
self._add_handler_with_cleanup(self.colorlog, handlers.ColorHandler)
@ -1040,7 +1041,7 @@ class FancyRecordTestCase(LogTestBase):
fake_resource = {'name': resource}
message = 'info'
self.colorlog.info(message, context=ctxt, resource=fake_resource)
expected = ('%s [%s]: [%s] %s\n' %
expected = ('%s [%s]: [%s] %s\033[00m\n' %
(color, ctxt.request_id, resource, message))
self.assertEqual(expected, self.stream.getvalue())
@ -1053,7 +1054,7 @@ class FancyRecordTestCase(LogTestBase):
'id': resource_id}
message = 'info'
self.colorlog.info(message, context=ctxt, resource=fake_resource)
expected = ('%s [%s]: [%s-%s] %s\n' %
expected = ('%s [%s]: [%s-%s] %s\033[00m\n' %
(color, ctxt.request_id, type, resource_id, message))
self.assertEqual(expected, self.stream.getvalue())