Python Forum

Full Version: How to left align logging messages
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I use the below code, and I want the messages to be left-aligned, meaning I want to align the columns.

import logging
from datetime import datetime

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s.%(msecs)04d:%(levelname)s: %(message)s',
                    filename=('mylog'+datetime.today().strftime('%Y%m%d_%H%M%S')+".txt"),
                    filemode='w',datefmt='%Y-%m-%d %H:%M:%S')
logging.debug('A debug message')
logging.info('Info message')
logging.warning('Warning message')
current output:
2020-06-27 11:52:26.201:DEBUG: A debug message
2020-06-27 11:52:26.202:INFO: Info message
2020-06-27 11:52:26.202:WARNING: Warning message
desired output:

2020-06-27 11:52:26.201:DEBUG:   A debug message
2020-06-27 11:52:26.202:INFO:    Info message
2020-06-27 11:52:26.202:WARNING: Warning message
The maximum you would need would be 8 spaces for CRITICAL. So tell it you want to pad to 8 spaces and use a hyphen for left alignment.

Change
    format='%(asctime)s.%(msecs)04d:%(levelname)s: %(message)s',
to

    format='%(asctime)s.%(msecs)04d:%(levelname)-8s: %(message)s',
Output:
2020-06-26 22:42:13.0384:DEBUG : A debug message 2020-06-26 22:42:13.0384:INFO : Info message 2020-06-26 22:42:13.0384:WARNING : Warning message 2020-06-26 22:42:13.0385:CRITICAL: Critical
(or -7 if you want WARNING to be the max and would put up with a bump if a CRITICAL ever appeared).
How can we decide -8s or -7s or any other like -xs
For logging (where you don't want to delay the messages), you just need to decide ahead of time what you want. You know that CRITICAL is the longest possible message there, so 8 makes sense.

For normal output, you might want to examine all of the strings and then figure out which is the longest. But you have to wait for all the output to be generated to make that decision. That doesn't make sense for logging where you want the information to be available quickly.