Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup python.logging format using f-string style

I'm writing an app using python 3.7 and want to use only f-strings in it.

I'm using python logging module in order to log my application correctly, and I want to use a specific format but the documentation (and the web) only example how to change the format using %-strings. I was wondering whether there is an option to set the logger format using f-strings

LOG_FORAMT = ('%(levelname)s -10s %(asctime)s -10s %(message)s') # Known example

f-LOG_FORMAT = (f'{logger.levelname} -10s') # Something like that?
like image 572
kaki gadol Avatar asked May 23 '19 06:05

kaki gadol


1 Answers

You can initialize logging.Formatter with argument style set to "{".

Example

formatter = logging.Formatter("{processName:<12} {message} ({filename}:{lineno})", style="{")

Available options for style are documented.

After this attach the formatter to a handler and add the handler to your desired logger(s).

If you are using logging.basicConfig you can set it with the following way:

logging.basicConfig(format="{processName:<12} {message} ({filename}:{lineno})", style="{")
like image 142
ldub Avatar answered Sep 28 '22 09:09

ldub