madzak / python-json-logger

Json Formatter for the standard python logger
BSD 2-Clause "Simplified" License
1.74k stars 231 forks source link

Only "%" style is supported #74

Closed haizaar closed 1 year ago

haizaar commented 5 years ago

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 commented 5 years ago

For "{" style you can do:

     def parse(self):
        field_spec = string.Formatter().parse(self._fmt)
        return [s[1] for s in field_spec]
xmo-odoo commented 4 years ago

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

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.