Skip to content

Commit

Permalink
fix(console_logger): serialize objects
Browse files Browse the repository at this point in the history
  • Loading branch information
serhez committed May 22, 2024
1 parent f4255e4 commit f350cfa
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 12 deletions.
4 changes: 4 additions & 0 deletions mloggers/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
"""
A collection of loggers well-suited for machine learning experiments.
"""

from ._log_levels import LogLevel, register_level
from .console_logger import ConsoleLogger
from .file_logger import FileLogger
Expand Down
33 changes: 22 additions & 11 deletions mloggers/console_logger.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import json
from datetime import datetime
from typing import Any

Expand All @@ -7,6 +6,7 @@

from mloggers._log_levels import LogLevel, _log_level_properties
from mloggers.logger import Logger
from mloggers.utils import serialize


class ConsoleLogger(Logger):
Expand Down Expand Up @@ -42,23 +42,21 @@ def log(
else:
level_clr = colored(level_str, "green")

# The first level of the dictionary is printed as a multiline
# indented message.
# The rest of the levels are printed as a single line
# prettifyed depending on the type of the value.
# The first level of the dictionary is printed as a multiline indented message.
# The rest of the levels are printed as a single line prettifyed depending on the type of the value.

# Handle multiple messages
if len(messages) > 1:
messages = list(messages)
# If the messages are strings, join them into a single string.
# If the messages are strings, join them into a single string
if all(
hasattr(message, "__str__")
and callable(getattr(message, "__str__"))
and not isinstance(message, dict)
for message in messages
):
messages = " ".join([str(message) for message in messages])
# If the messages are dictionaries, log them separately.
# If the messages are dictionaries, log them separately
else:
for message in messages:
self.log(message, level=level)
Expand All @@ -75,15 +73,28 @@ def log(

if isinstance(value, float):
print(f"{level_clr}{time} {key}: {value:.5f}")
elif isinstance(value, dict | list):
value = json.dumps(value, indent=4)
print(f"{level_clr}{time} {key}: {value}")
elif value is None: # Used for headers, titles, etc.
print(f"{level_clr}{time} {key}")
else:
print(f"{level_clr}{time} {key}: {value}")
try:
value = serialize(value)
print(f"{level_clr}{time} {key}: {value}")
except TypeError as e:
print(
f'{colored("[ERROR]", "red")} [ConsoleLogger] Could not convert the message to a JSON serializable format: {e}'
)
continue

first = False

elif hasattr(messages, "__str__") and callable(getattr(messages, "__str__")):
print(f"{level_clr}{time} {str(messages)}")

else:
try:
serialized = serialize(messages)
print(f"{level_clr}{time} {serialized}")
except TypeError as e:
print(
f'{colored("[ERROR]", "red")} [ConsoleLogger] Could not convert the message to a JSON serializable format: {e}'
)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "mloggers"
version = "1.3.3"
version = "1.3.4"
authors = [
{ name = "Sergio Hernandez Gutierrez", email = "[email protected]" },
{ name = "Matteo Merler", email = "[email protected]" },
Expand Down

0 comments on commit f350cfa

Please sign in to comment.