4

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).

vvvvv
  • 25,404
  • 19
  • 49
  • 81
v1z3
  • 137
  • 2
  • 9
  • That isn't possible. The style parameter is only for the format that you can set with the `format` parameter, or by using a `Formatter` , but not when calling the log methods. – blues Apr 06 '21 at 06:01
  • I see now, thank you. – v1z3 Apr 06 '21 at 08:48
  • @blue this is possible with python 3.2+. see https://stackoverflow.com/a/75715402/1595865 – loopbackbee Mar 12 '23 at 20:51

2 Answers2

2

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)
Jacob Lee
  • 4,405
  • 2
  • 16
  • 37
2

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

Pierre.Sassoulas
  • 3,733
  • 3
  • 33
  • 48