Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 613
humanica Avatar asked Jul 25 '19 14:07

humanica


People also ask

How do I use logging config in Python?

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.

What is Formatter logging?

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.


1 Answers

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
like image 179
finefoot Avatar answered Sep 21 '22 09:09

finefoot