Skip to content

Commit

Permalink
Add support for multiline logs and exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
furbrain committed Jun 20, 2024
1 parent c9c6450 commit 39a7927
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 8 deletions.
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)

0 comments on commit 39a7927

Please sign in to comment.