Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix logging of a single non-serializable object #13

Merged
merged 1 commit into from
May 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions examples/serialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,20 @@


class CustomClass:
"""Dummy class to demo logging."""
"""Dummy class without __str__ method to demo logging."""

def __init__(self, value):
"""Initialize CustomClass object."""
self._value = value


class CustomClassConvertable():
"""Dummy class with __str__ method to demo logging."""

def __init__(self, value):
"""Initialize CustomClassConvertable object."""
self._value = value

def __str__(self):
"""Convert CustomClass to string."""
return "CustomClass: {}".format(self._value)
Expand Down Expand Up @@ -61,7 +69,8 @@ def main():
logger.info("Test log with multiple str parameters: %s %s",
"test1", "test2")

custom_object = CustomClass('test')
custom_object = CustomClassConvertable('test')
# formatting uses __repr__ if __str__ method isn't available
logger.info("Test logging of custom obj: %s", custom_object)
# log record will contain the following values:
# args: <__main__.CustomClass object at 0x7f3147041c88>
Expand All @@ -79,6 +88,12 @@ def main():
"custom_field_json": {"a": "test", "b": "test"}
})

# logging single object without formatting
custom_object_with_str = CustomClassConvertable('test w/ str method')
logger.info(custom_object_with_str) # object has __str__ method
custom_object_wo_str = CustomClass('test w/o str method')
logger.info(custom_object_wo_str) # str() will use repr()


if __name__ == '__main__':
main()
4 changes: 4 additions & 0 deletions kafka_logger/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,10 @@ def prepare_record_dict(self, record):
# but it is not 1:1 - logging "inf" float
# causes _jsonparsefailure error in ELK
value = tuple(repr(arg) for arg in value)
if key == "msg" and not isinstance(value, basestring):
# msg contains custom class object
# if there is no formatting in the logging call
value = str(value)
rec[key] = "" if value is None else value

return rec
Expand Down