Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you shorten logging headers when using python logging `%(funcName)s`?

Sometimes I configure the python logging formatter using the %(funcName)s. But I don't like this when the function names are really long.

Can you shorten logging headers when using python logging %(funcName)s? If yes, how?

Can you say... limit the total number of characters to like 10 characters?

like image 288
Trevor Boyd Smith Avatar asked Feb 18 '26 23:02

Trevor Boyd Smith


1 Answers

The %(...)s items in the logging format string are % replacements, and you can limit the length of a string replacement by doing something like %(funcName).10s

e.g.

import logging

logging.basicConfig(
    format='%(funcName).10s %(message)s',
    level=logging.INFO,
)

logger = logging.getLogger()

def short():
    logger.info("I'm only little!")

def really_really_really_really_long():
    logger.info("I'm really long")

short()
really_really_really_really_long()

gives

andy@batman[17:54:01]:~$ p tmp_x.py 
short I'm only little!
really_rea I'm really long
like image 125
Andrew Gelnar Avatar answered Feb 20 '26 11:02

Andrew Gelnar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!