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

Add support for multiline logs and exceptions #60

Merged
merged 1 commit into from
Jun 23, 2024
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
42 changes: 35 additions & 7 deletions adafruit_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,15 @@ def __init__(self, stream: Optional[WriteableStream] = None) -> None:
self.stream = stream
"""The stream to log to"""

def format(self, record: LogRecord) -> str:
"""Generate a string to log

:param record: The record (message object) to be logged
"""
text = super().format(record)
lines = text.splitlines()
return self.terminator.join(lines) + self.terminator

def emit(self, record: LogRecord) -> None:
"""Send a message to the console.

Expand All @@ -224,6 +233,8 @@ class FileHandler(StreamHandler):
:param str mode: Whether to write ('w') or append ('a'); default is to append
"""

terminator = "\r\n"

def __init__(self, filename: str, mode: str = "a") -> None:
# pylint: disable=consider-using-with
if mode == "r":
Expand All @@ -235,13 +246,6 @@ def close(self) -> None:
self.stream.flush()
self.stream.close()

def format(self, record: LogRecord) -> str:
"""Generate a string to log

:param record: The record (message object) to be logged
"""
return super().format(record) + "\r\n"

def emit(self, record: LogRecord) -> None:
"""Generate the message and write it to the file.

Expand Down Expand Up @@ -538,3 +542,27 @@ def critical(self, msg: str, *args) -> None:
can be empty
"""
self._log(CRITICAL, msg, *args)

# pylint: disable=no-value-for-parameter; value and tb are optional for traceback
def exception(self, err: Exception) -> None:
"""Convenience method for logging an ERROR with exception information.

:param Exception err: the exception to be logged
"""
try:
# pylint: disable=import-outside-toplevel; not available on all boards
import traceback
except ImportError:
self._log(
ERROR,
"%s: %s (No traceback on this board)",
err.__class__.__name__,
str(err),
)
else:
lines = [str(err)] + traceback.format_exception(err)
lines = str(err) + "\n".join(lines)
# some of the returned strings from format_exception already have newlines in them,
# so we can't add the indent in the above line - needs to be done separately
lines = lines.replace("\n", "\n ")
self._log(ERROR, lines)
9 changes: 8 additions & 1 deletion examples/logging_simpletest.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@
logger.setLevel(logging.ERROR)
logger.info("Stream Handler: Info message")
logger.error("Stream Handler: Error message")

try:
raise RuntimeError("Test exception handling")
except RuntimeError as e:
logger.exception(e)
# This should produce no output at all.

null_logger = logging.getLogger("null")
Expand All @@ -36,3 +39,7 @@
null_logger.setLevel(logging.ERROR)
null_logger.info("Null Handler: Info message")
null_logger.error("Null Handler: Error message")
try:
raise RuntimeError("Test exception handling")
except RuntimeError as e:
null_logger.exception(e)
Loading