Skip to content

Commit

Permalink
Enhanced logger encoder (#28)
Browse files Browse the repository at this point in the history
  • Loading branch information
liranbg authored Apr 5, 2021
1 parent 59687c1 commit 7efb698
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
13 changes: 11 additions & 2 deletions nuclio_sdk/json_encoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
29 changes: 26 additions & 3 deletions nuclio_sdk/test/test_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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(),
)

0 comments on commit 7efb698

Please sign in to comment.