If you know the longest log level name in advance, for
example, if you are only going to use the standard log
levels, a simple solution might be to set the formatter,
as in the first code block below (output same as flexible
solution):
# Set logging format and lowest logging level
logging.basicConfig(format='[{levelname:^8s}] - {message:s}',
style='{',
level=logging.DEBUG)
for i,nm in logging._levelToName.items():
logging.log(i, f"This is a {nm.lower().strip()} level message")
A flexible solution, where the names of the logging levels
are not known in advance, is to rename the numeric log
levels of the logging module. This solution is
demonstrated in the code below.
The code sets a basic formatter to replicate the requested
output messages, and sets the logging level to the lowest
level.
After determining the longest logging level name, it sets
all logging level names to their original names, centered,
with extra padding.
# Set logging format and lowest logging level
logging.basicConfig(format='[%(levelname)s] - %(message)s',
level=logging.DEBUG)
# Determine longest loggging name
longest = max(logging._levelToName.items(), key=lambda x: len(x[1]))
maxLen = len(longest[1].strip())
# Reformat logging level names
for i,nm in logging._levelToName.items():
# See https://stackoverflow.com/a/69630856/5660315
logging.addLevelName(i, "{0:^{width}}".format(nm, width=maxLen))
logging.log(i, f"This is a {nm.lower().strip()} level message")
Output:
[CRITICAL] - This is a critical level message
[ ERROR ] - This is a error level message
[WARNING ] - This is a warning level message
[ INFO ] - This is a info level message
[ DEBUG ] - This is a debug level message