vvvvv
vvvvv

Reputation: 31700

Right/Left align several values together in Python Logging Formatter

In order to left-align the levelname value inside the logs with 8 chars, one can use %(levelname)-8s.

import logging

logging.basicConfig(
    level=logging.DEBUG,
    format="[%(asctime)s] (%(module)s:%(funcName)s::%(lineno)s) - %(levelname)-8s - %(message)s ",
    handlers=[logging.StreamHandler()]
)

def fake_function():
    logging.info("This is a info message")

fake_function()

will give:

[2023-01-09 18:03:48,842] (example:fake_function::12)-100s -     INFO - This is a info message

However, I am more interested in left-aligning the 3 values (%(module)s:%(funcName)s::%(lineno)s. I want to do it in one block, ie having:

[2023-01-09 18:07:14,743] (example:fake_function::12)                     - INFO     - This is a info message 
[2023-01-09 18:07:14,745] (another_example:another_fake_function::123456) - INFO     - This is a info message 
[2023-01-09 18:07:14,758] (a:b::1)                                        - INFO     - This is a info message 

I know I could left-align these 3 values separately, but it would leave a lot of spaces between the module, the funcName and the lineno making it too messy for my taste.

I tried to use %(%(module)s:%(funcName)s::%(lineno)s)-100s but it did not work (it simply printed -100s).

Is there a way to right/left-align several values from the logs together as one?

Upvotes: 2

Views: 339

Answers (1)

Vinay Sajip
Vinay Sajip

Reputation: 99385

You can set up a filter which combines those three items into one, and ensure it's added to all handlers which need to output them in this way, and then reference the location in your format - as in this example:

import logging

def combining_filter(record):
    record.location = '(%s:%s:%s)' % (record.module, record.funcName, record.lineno)
    return True

h = logging.StreamHandler()
h.addFilter(combining_filter)

logging.basicConfig(
    level=logging.DEBUG,
    format="[%(asctime)s] %(location)-40s - %(levelname)-8s - %(message)s ",
    handlers=[h]
)

def fake_function():
    logging.info("This is a info message")

fake_function()

which should print

[2023-01-09 17:53:49,677] (so_75060822:fake_function:17)           - INFO     - This is a info message 

Upvotes: 1

Related Questions