How to properly format the python logging formatter?

humanica picture humanica · Jul 25, 2019 · Viewed 7.7k times · Source

I try to format the way my Python logging formatter outputs strings. I wrote a minimalistic example to show the problem:

import logging
from pathlib import Path

# create auxiliary variables
loggerName = Path(__file__).stem

# create logging formatter
logFormatter = logging.Formatter(fmt=' %(name)s :: %(levelname)s :: %(message)s')

# create logger
logger = logging.getLogger(loggerName)
logger.setLevel(logging.DEBUG)

# create console handler
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.WARNING)
consoleHandler.setFormatter(logFormatter)

# Add console handler to logger
logger.addHandler(consoleHandler)

# Test
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')

The script will give a an output without proper formatting:

logger :: WARNING :: warn message
logger :: ERROR :: error message
logger :: CRITICAL :: critical message

I would like to change the formatting to keep left side of my logging in order:

logger :: WARNING  :: warn message
logger :: ERROR    :: error message
logger :: CRITICAL :: critical message

Answer

finefoot picture finefoot · Jul 25, 2019

The format string uses Python's regular %-formatting, also called printf-style formatting. You can read more about it in the docs at https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting What you're looking for is a minimum field width paired with the - flag:

'-' The converted value is left adjusted

So, with

logFormatter = logging.Formatter(fmt=' %(name)s :: %(levelname)-8s :: %(message)s')

you will get the following output:

 test :: WARNING  :: warn message
 test :: ERROR    :: error message
 test :: CRITICAL :: critical message