Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format logs so they print out in columns?

I have a project where different threads and functions are logging to the same StreamHandler() log in the console using different loglevels some of which are custom.

My log is formatted to do:

streamformatter = logging.Formatter(fmt='%(levelname)s:\t%(threadName)s:\t%(funcName)s:\t\t%(message)s', datefmt='%H:%M:%S')

This makes my log by default look garbled like this where it isnt really pretty to look at or easy to see when what function is being called and from which thread.

INFO:   COM14-fwcif-listener :  _receive_v32:       my_success: Sending 24 lines to formatter
DB_TRACE:   COM14-fwcif-listener :  _format_and_log_v32:        {"prompt": "undef-COM14", "x_type": "tracelogentry", "y_time": 1392695506.044583, "z_msg": "...."}
INFO:   COM13-fwutil-listener:  _receive_v32:       my_success: Sending 10 lines to formatter
DB_TRACE:   COM13-fwutil-listener:  _format_and_log_v32:        {"prompt": "undef-COM13", "x_type": "tracelogentry", "y_time": 1392695507.356714, "z_msg": "...."}
INFO:   MainThread: _parse:     my_resolve after 4.9784979820251465 seconds and 29 vs 8 attempts
MY_INFO:    MainThread: _parse:     my_success for cmd "trig" =>> "not ready". COM12.ISREADY now set to True
INFO:   MainThread: send:       my_success. Lock being released: <_thread.RLock owner=7512 count=1> with cmd "format c:" and state COM12.ISREADY = False
INFO:   COM12-fwmain-listener:  _receive_v32:       my_success: Number of lines split by S65 is 2 of 16 total lines
INFO:   COM12-fwmain-listener:  _format_and_log_v32:        my_resolve "S65>" added as COM12.lastlinefragment
INFO:   COM12-fwmain-listener:  _format_and_log_v32:        my_success: 575 chars written to log.   Prompt and type detected is "S65>" and "replylogentry: format"
DB_REPLY:   COM12-fwmain-listener:  _format_and_log_v32:        {"prompt": "S65>", "x_type": "replylogentry: format", "y_time": 1392695510.41302, "z_msg": "..."}
INFO:   MainThread: _parse:     my_resolve  searching for "format"=>"Unknown command" in string "..."
like image 364
Paul H Avatar asked Dec 17 '25 15:12

Paul H


1 Answers

The width of each token can be specified in the streamformatter in this way to produce a log output in fixed colons:

streamformatter = logging.Formatter(fmt='%(levelname)-10s:  %(threadName)-20s: %(funcName)-20s:  %(message)s', datefmt='%H:%M:%S')
like image 157
Paul H Avatar answered Dec 19 '25 03:12

Paul H