Skip to content

Commit 0fd00ca

Browse files
authored
Merge pull request #13 from kusha/fix-single-nonserializable-arg
Fix logging of a single non-serializable object
2 parents fa6e372 + 663b3dd commit 0fd00ca

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

examples/serialize.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,20 @@
1111

1212

1313
class CustomClass:
14-
"""Dummy class to demo logging."""
14+
"""Dummy class without __str__ method to demo logging."""
1515

1616
def __init__(self, value):
1717
"""Initialize CustomClass object."""
1818
self._value = value
1919

20+
21+
class CustomClassConvertable():
22+
"""Dummy class with __str__ method to demo logging."""
23+
24+
def __init__(self, value):
25+
"""Initialize CustomClassConvertable object."""
26+
self._value = value
27+
2028
def __str__(self):
2129
"""Convert CustomClass to string."""
2230
return "CustomClass: {}".format(self._value)
@@ -61,7 +69,8 @@ def main():
6169
logger.info("Test log with multiple str parameters: %s %s",
6270
"test1", "test2")
6371

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

91+
# logging single object without formatting
92+
custom_object_with_str = CustomClassConvertable('test w/ str method')
93+
logger.info(custom_object_with_str) # object has __str__ method
94+
custom_object_wo_str = CustomClass('test w/o str method')
95+
logger.info(custom_object_wo_str) # str() will use repr()
96+
8297

8398
if __name__ == '__main__':
8499
main()

kafka_logger/handlers.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,10 @@ def prepare_record_dict(self, record):
161161
# but it is not 1:1 - logging "inf" float
162162
# causes _jsonparsefailure error in ELK
163163
value = tuple(repr(arg) for arg in value)
164+
if key == "msg" and not isinstance(value, basestring):
165+
# msg contains custom class object
166+
# if there is no formatting in the logging call
167+
value = str(value)
164168
rec[key] = "" if value is None else value
165169

166170
return rec

0 commit comments

Comments
 (0)