Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do new-style lazy formatting python logging [duplicate]

This concerns pylint and python logging. The following code doesn't work:

logging.basicConfig(level=logging.DEBUG, format='{message}', style='{')
log.debug('url {}', url)

It raises:

  File "/usr/lib/python3.9/logging/__init__.py", line 363, in getMessage
    msg = msg % self.args
TypeError: not all arguments converted during string formatting

How do I make the logging work with the {} style instead of %s?

I'm using this basicConfig while testing my modules but I can also have a more advanced formatter in my package. The reason I started exploring this is because pylint was complaining when I used f-strings, but also when I was using old formatting with (%s).

like image 626
v1z3 Avatar asked Oct 26 '25 12:10

v1z3


2 Answers

The logging lazy formatting simply consists of "%s" placeholder then, following the string and separated by commas, the values to replace those placeholders.

In this case:

logging.basicConfig(level=logging.DEBUG, format='%(message)s')
log.debug("url %s", url)
like image 192
Jacob Lee Avatar answered Oct 29 '25 02:10

Jacob Lee


You can use logging-format-style=new in your pylintrc.

Since pylint 2.2:

logging-format-style is a new option for the logging checker for usage of str.format() style format strings in calls to loggers.

It accepts two options: --logging-format-style=old for using % style formatting, which is the assumed default, and --logging-format-style=new for using {} style formatting.

There is also a fstring style, see this very good answer: https://stackoverflow.com/a/59027338/2519059

like image 33
Pierre.Sassoulas Avatar answered Oct 29 '25 02:10

Pierre.Sassoulas



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!