8

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?
kaki gadol
  • 1,116
  • 1
  • 14
  • 34
  • 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. – Ben May 23 '19 at 06:47
  • 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.. – kaki gadol May 23 '19 at 08:17

1 Answers1

16

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="{")
pfabri
  • 885
  • 1
  • 9
  • 25
ldub
  • 176
  • 2
  • 3