1111
1212
1313class 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
8398if __name__ == '__main__' :
8499 main ()
0 commit comments