python-json-logger
python-json-logger copied to clipboard
Only "%" style is supported
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.
For "{" style you can do:
def parse(self):
field_spec = string.Formatter().parse(self._fmt)
return [s[1] for s in field_spec]
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_mapfor{ - using
Template.substitutefor${(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.