logging: Extend LEVELNAME_FMT_REGEX

This commit is contained in:
Thomas Hisch 2019-05-29 23:15:34 +02:00
parent 28ac469eaa
commit ef053193b5
3 changed files with 28 additions and 1 deletions

View File

@ -0,0 +1,2 @@
Colorize level names when the level in the logging format is formatted using
'%(levelname).Xs' (truncated fixed width alignment), where X is an integer.

View File

@ -39,7 +39,7 @@ class ColoredLevelFormatter(logging.Formatter):
logging.DEBUG: {"purple"}, logging.DEBUG: {"purple"},
logging.NOTSET: set(), logging.NOTSET: set(),
} }
LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-]?\d*s)") LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*s)")
def __init__(self, terminalwriter, *args, **kwargs): def __init__(self, terminalwriter, *args, **kwargs):
super(ColoredLevelFormatter, self).__init__(*args, **kwargs) super(ColoredLevelFormatter, self).__init__(*args, **kwargs)

View File

@ -65,3 +65,28 @@ def test_multiline_message():
"dummypath 10 INFO Test Message line1\n" "dummypath 10 INFO Test Message line1\n"
" line2" " line2"
) )
def test_colored_short_level():
logfmt = "%(levelname).1s %(message)s"
record = logging.LogRecord(
name="dummy",
level=logging.INFO,
pathname="dummypath",
lineno=10,
msg="Test Message",
args=(),
exc_info=False,
)
class ColorConfig(object):
class option(object):
pass
tw = py.io.TerminalWriter()
tw.hasmarkup = True
formatter = ColoredLevelFormatter(tw, logfmt)
output = formatter.format(record)
# the I (of INFO) is colored
assert output == ("\x1b[32mI\x1b[0m Test Message")