How to left align logging messages - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to left align logging messages (/thread-27919.html) |
How to left align logging messages - Mekala - Jun-27-2020 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 messagedesired 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 RE: How to left align logging messages - bowlofred - Jun-27-2020 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', (or -7 if you want WARNING to be the max and would put up with a bump if a CRITICAL ever appeared).
RE: How to left align logging messages - Mekala - Jun-28-2020 How can we decide -8s or -7s or any other like -xs RE: How to left align logging messages - bowlofred - Jun-28-2020 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. |