How to Properly Format the Python Logging Formatter?

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
0

1 Answer

The format string uses Python's regular %-formatting, also called printf-style formatting. You can read more about it in the docs at 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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest