python-json-logger icon indicating copy to clipboard operation
python-json-logger copied to clipboard

Only "%" style is supported

Open haizaar opened this issue 5 years ago • 2 comments

Since Python 3.2, formatters support new "{" and "${" styles, however JsonFormatter's parse method explicitly expects "%" notation.

This results in empty message is e.g. {message} used as logger formatting string.

haizaar avatar Mar 28 '19 06:03 haizaar

For "{" style you can do:

     def parse(self):
        field_spec = string.Formatter().parse(self._fmt)
        return [s[1] for s in field_spec]

haizaar avatar Mar 28 '19 06:03 haizaar

An alternative method which should work is to "render" the format string using a custom Mapping object which records which key was accessed (and returns garbage):

  • using str.format_map for {
  • using Template.substitute for ${ (it can take a positional mapping)
  • using the normal % for %
import string

class A:
    def __init__(self):
        self.fields = set()
    def __getitem__(self, key):
        self.fields.add(key)
        return 0 # %d / %f do not appreciate getting a string while %s is fine with a number

for render in [
        lambda o: '%(foo)s %(bar)d' % o,
        '{foo} {bar}'.format_map,
        string.Template("$foo $bar").substitute,
]:
    obj = A()
    render(obj)
    print(obj.fields)

yields the relevant keys for all three methods. The one issue would be that this method would behave "strictly" for the % case, and cases like #86 (invalid format strings which happen to be understood by json-logger) would be completely broken. So maybe this should only be used for { and ${ formats.

xmo-odoo avatar Nov 19 '19 11:11 xmo-odoo