Skip to content

logging: Extend LEVELNAME_FMT_REGEX #5335

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog/5335.bugfix.rst
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion src/_pytest/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ class ColoredLevelFormatter(logging.Formatter):
logging.DEBUG: {"purple"},
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):
super(ColoredLevelFormatter, self).__init__(*args, **kwargs)
Expand Down
25 changes: 25 additions & 0 deletions testing/logging/test_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,28 @@ def test_multiline_message():
"dummypath 10 INFO Test Message line1\n"
" 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")