Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logging: left align with brackets

I would like to format the logger with brackets and left-align the text.

formatter = logging.Formatter('[%(asctime)s] [%(levelname)-8s] [%(funcName)-12s]   %(message)s')

Here is the result

[2019-09-13 16:22:56,050] [INFO    ] [main        ]   Message 1
[2019-09-13 16:22:56,050] [DEBUG   ] [do_debug    ]   Message 2
[2019-09-13 16:22:56,050] [WARNING ] [do_warning  ]   Message 3

But i would like to get something like this

[2019-09-13 16:22:56,050] [INFO]     [main]           Message 1
[2019-09-13 16:22:56,050] [DEBUG]    [do_debug]       Message 2
[2019-09-13 16:22:56,050] [WARNING]  [do_warning]     Message 3
like image 271
cogimi Avatar asked Sep 13 '19 14:09

cogimi


1 Answers

This is easy enough to do, as the following example shows:

import logging

logger = logging.getLogger(__name__)

def do_debug():
    logger.debug('Message 2')

def do_warning():
    logger.warning('Message 3')

def main():
    logger.info('Message 1')
    do_debug()
    do_warning()

def fmt_filter(record):
    record.levelname = '[%s]' % record.levelname
    record.funcName = '[%s]' % record.funcName
    return True

if __name__ == '__main__':
    FMT = '[%(asctime)s] %(levelname)-10s %(funcName)-12s   %(message)s'
    f = logging.Formatter(FMT)
    h = logging.StreamHandler()
    h.setFormatter(f)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(h)
    logger.addFilter(fmt_filter)
    main()

When run, the above script prints:

[2020-02-01 21:36:48,758] [INFO]     [main]         Message 1
[2020-02-01 21:36:48,758] [DEBUG]    [do_debug]     Message 2
[2020-02-01 21:36:48,774] [WARNING]  [do_warning]   Message 3

You should be able to adapt the above example to your specific need, e.g. where you apply the filter, what handler you use, etc.

like image 70
Vinay Sajip Avatar answered Nov 12 '22 23:11

Vinay Sajip