Skip to content

Commit cbfea81

Browse files
authored
Merge pull request #60 from furbrain/main
Add support for multiline logs and exceptions
2 parents c9c6450 + 39a7927 commit cbfea81

File tree

2 files changed

+43
-8
lines changed

2 files changed

+43
-8
lines changed

adafruit_logging.py

+35-7
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,15 @@ def __init__(self, stream: Optional[WriteableStream] = None) -> None:
202202
self.stream = stream
203203
"""The stream to log to"""
204204

205+
def format(self, record: LogRecord) -> str:
206+
"""Generate a string to log
207+
208+
:param record: The record (message object) to be logged
209+
"""
210+
text = super().format(record)
211+
lines = text.splitlines()
212+
return self.terminator.join(lines) + self.terminator
213+
205214
def emit(self, record: LogRecord) -> None:
206215
"""Send a message to the console.
207216
@@ -224,6 +233,8 @@ class FileHandler(StreamHandler):
224233
:param str mode: Whether to write ('w') or append ('a'); default is to append
225234
"""
226235

236+
terminator = "\r\n"
237+
227238
def __init__(self, filename: str, mode: str = "a") -> None:
228239
# pylint: disable=consider-using-with
229240
if mode == "r":
@@ -235,13 +246,6 @@ def close(self) -> None:
235246
self.stream.flush()
236247
self.stream.close()
237248

238-
def format(self, record: LogRecord) -> str:
239-
"""Generate a string to log
240-
241-
:param record: The record (message object) to be logged
242-
"""
243-
return super().format(record) + "\r\n"
244-
245249
def emit(self, record: LogRecord) -> None:
246250
"""Generate the message and write it to the file.
247251
@@ -538,3 +542,27 @@ def critical(self, msg: str, *args) -> None:
538542
can be empty
539543
"""
540544
self._log(CRITICAL, msg, *args)
545+
546+
# pylint: disable=no-value-for-parameter; value and tb are optional for traceback
547+
def exception(self, err: Exception) -> None:
548+
"""Convenience method for logging an ERROR with exception information.
549+
550+
:param Exception err: the exception to be logged
551+
"""
552+
try:
553+
# pylint: disable=import-outside-toplevel; not available on all boards
554+
import traceback
555+
except ImportError:
556+
self._log(
557+
ERROR,
558+
"%s: %s (No traceback on this board)",
559+
err.__class__.__name__,
560+
str(err),
561+
)
562+
else:
563+
lines = [str(err)] + traceback.format_exception(err)
564+
lines = str(err) + "\n".join(lines)
565+
# some of the returned strings from format_exception already have newlines in them,
566+
# so we can't add the indent in the above line - needs to be done separately
567+
lines = lines.replace("\n", "\n ")
568+
self._log(ERROR, lines)

examples/logging_simpletest.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,10 @@
2525
logger.setLevel(logging.ERROR)
2626
logger.info("Stream Handler: Info message")
2727
logger.error("Stream Handler: Error message")
28-
28+
try:
29+
raise RuntimeError("Test exception handling")
30+
except RuntimeError as e:
31+
logger.exception(e)
2932
# This should produce no output at all.
3033

3134
null_logger = logging.getLogger("null")
@@ -36,3 +39,7 @@
3639
null_logger.setLevel(logging.ERROR)
3740
null_logger.info("Null Handler: Info message")
3841
null_logger.error("Null Handler: Error message")
42+
try:
43+
raise RuntimeError("Test exception handling")
44+
except RuntimeError as e:
45+
null_logger.exception(e)

0 commit comments

Comments
 (0)