From 7efb698e8aaf379f7eb10855c6f885c0c0ac4d87 Mon Sep 17 00:00:00 2001 From: Liran BG Date: Mon, 5 Apr 2021 09:58:24 -0400 Subject: [PATCH] Enhanced logger encoder (#28) --- nuclio_sdk/json_encoder.py | 13 +++++++++++-- nuclio_sdk/test/test_logger.py | 29 ++++++++++++++++++++++++++--- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/nuclio_sdk/json_encoder.py b/nuclio_sdk/json_encoder.py index e8cd84c..38b8791 100644 --- a/nuclio_sdk/json_encoder.py +++ b/nuclio_sdk/json_encoder.py @@ -19,5 +19,14 @@ class Encoder(json.JSONEncoder): def default(self, obj): - # Let the base class default method raise the TypeError - return json.JSONEncoder.default(self, obj) + # EAFP all the way. Leave the unused "exc" in for debugging ease + try: + return obj.__log__() + except Exception as exc: # noqa + try: + return obj.__repr__() + except Exception as exc: # noqa + try: + return str(obj) + except Exception as exc: + return "Unable to serialize object: {0}".format(exc) diff --git a/nuclio_sdk/test/test_logger.py b/nuclio_sdk/test/test_logger.py index b85fd93..8622efb 100644 --- a/nuclio_sdk/test/test_logger.py +++ b/nuclio_sdk/test/test_logger.py @@ -12,7 +12,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -import unittest import logging import datetime import io @@ -53,7 +52,6 @@ def test_log_with_number(self): self.assertIn("TestC", self._io.getvalue()) self.assertIn('"with": {"number": 1}', self._io.getvalue()) - @unittest.skip("currently unsupported") def test_log_with_date(self): """ log line with datetime kwarg @@ -62,4 +60,29 @@ def test_log_with_date(self): date = datetime.datetime.strptime("Oct 1 2020", "%b %d %Y") self._logger.debug_with("TestD", date=date) self.assertIn("TestD", self._io.getvalue()) - self.assertIn('"with": {"date": "2020-10-01T00:00:00"}', self._io.getvalue()) + self.assertIn( + '"with": {"date": "datetime.datetime(2020, 10, 1, 0, 0)"}', + self._io.getvalue(), + ) + + def test_fail_to_log(self): + """ + Do not fail logging when an object is not log-able + """ + + class SomeObject(object): + def __str__(self): + raise Exception("I am not a string") + + def __repr__(self): + raise Exception("Not yet a repr") + + def __log__(self): + raise Exception("All I need is time") + + self._logger.debug_with("TestD", some_instance=SomeObject()) + self.assertIn("TestD", self._io.getvalue()) + self.assertIn( + '"with": {"some_instance": "Unable to serialize object: I am not a string"}', + self._io.getvalue(), + )