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

1

9

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?
Kweilin answered 23/5, 2019 at 6:35 Comment(2)
Set the format like that, then just use fstrings in your message: logger.error(f"bad var: {var}"). So, in practice, you dont have to deal with weird format strings past your log setup.Aldrin
I have no problems with using f-strings in logging messages (logger.error() / logger.info() / etc...), I was just wondering whether there is an option to use f-string format in the log formatter..Kweilin
S
17

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="{")
Saccule answered 5/11, 2019 at 15:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.