Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

I attempt to organize the manner in which my Python logging formatter yields strings. I composed a moderate guide to show the issue: 

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 content will give a yield without legitimate arranging: 

logger :: WARNING :: warn message

logger :: ERROR :: error message

logger :: CRITICAL :: critical message

I might want to change the organizing to keep left half of my signing all together:

logger :: WARNING  :: warn message

logger :: ERROR    :: error message

logger :: CRITICAL :: critical message

1 Answer

0 votes
by (26.4k points)

The format string utilizes Python's customary %-organizing, likewise called printf-style formatting. You can peruse more about it in the docs at this link.

What you're searching for is a base field width combined with the - flag:

'-' The converted value is left adjusted

So, with

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

So, you will get the accompanying output:

 test :: WARNING  :: warn message

 test :: ERROR    :: error message

 test :: CRITICAL :: critical message

Want to learn python to get expertise in the concepts of python? Join python certification course and get certified

Related questions

0 votes
4 answers
asked Apr 7, 2021 in Python by laddulakshana (16.4k points)
0 votes
4 answers
+3 votes
3 answers
0 votes
1 answer

Browse Categories

...