Skip to content

Commit ed129b4

Browse files
committed
logging: Extend LEVELNAME_FMT_REGEX
1 parent 693c3b7 commit ed129b4

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

changelog/0000.feature.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Colorize level names when the level in the logging format is formatted using
2+
'%(levelname).Xs' (truncated fixed width alignment), where X is an integer.

src/_pytest/logging.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ class ColoredLevelFormatter(logging.Formatter):
3939
logging.DEBUG: {"purple"},
4040
logging.NOTSET: set(),
4141
}
42-
LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-]?\d*s)")
42+
LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*s)")
4343

4444
def __init__(self, terminalwriter, *args, **kwargs):
4545
super(ColoredLevelFormatter, self).__init__(*args, **kwargs)

testing/logging/test_formatter.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,3 +65,28 @@ def test_multiline_message():
6565
"dummypath 10 INFO Test Message line1\n"
6666
" line2"
6767
)
68+
69+
70+
def test_colored_short_level():
71+
logfmt = "%(levelname).1s %(message)s"
72+
73+
record = logging.LogRecord(
74+
name="dummy",
75+
level=logging.INFO,
76+
pathname="dummypath",
77+
lineno=10,
78+
msg="Test Message",
79+
args=(),
80+
exc_info=False,
81+
)
82+
83+
class ColorConfig(object):
84+
class option(object):
85+
pass
86+
87+
tw = py.io.TerminalWriter()
88+
tw.hasmarkup = True
89+
formatter = ColoredLevelFormatter(tw, logfmt)
90+
output = formatter.format(record)
91+
# the I (of INFO) is colored
92+
assert output == ("\x1b[32mI\x1b[0m Test Message")

0 commit comments

Comments
 (0)