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 json serialization error #206

Merged
merged 1 commit into from
Mar 24, 2025
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
2 changes: 0 additions & 2 deletions lib/pysquared/hardware/digitalio.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ def initialize_pin(
"""
logger.debug(
message="Initializing pin",
pin=pin,
direction=direction,
initial_value=initial_value,
)

Expand Down
13 changes: 12 additions & 1 deletion lib/pysquared/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,18 @@ def _log(self, level: str, level_value: int, message: str, **kwargs) -> None:
)
json_order.update(kwargs)

json_output = json.dumps(json_order)
try:
json_output = json.dumps(json_order)
except TypeError as e:
json_output = json.dumps(
OrderedDict(
[
("time", asctime),
("level", "ERROR"),
("msg", f"Failed to serialize log message: {e}"),
]
),
)

if self._can_print_this_level(level_value):
if self.colorized:
Expand Down
9 changes: 8 additions & 1 deletion tests/unit/lib/pysquared/test_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,14 @@ def test_critical_log(capsys, logger):
assert '"soft": "ware"' in captured.out
assert '"j": "20"' in captured.out
assert '"config": "king"' in captured.out
assert "OSError: Manually creating an OS Error" in captured.out


def test_type_error_log(capsys, logger):
logger.info("Testing type error", bad_arg=lambda x: x + 1)
captured = capsys.readouterr()
assert '"level": "ERROR"' in captured.out
assert "Failed to serialize log message:" in captured.out
assert "Object of type function is not JSON serializable" in captured.out


def test_debug_log_color(capsys, logger_color):
Expand Down