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
Logging in PythonYou can configure logging using the module and class functions or by creating a config file or a dictionary and loading it using fileConfig() or dictConfig() respectively. These are useful in case you want to change your logging configuration in a running application.
Log formatters format log messages so they can be used by various log handlers. Handlers can be configured with a log formatter that knows how to format log records. The event, which is represented by the log record object, is passed to the appropriate formatter by the handler.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With