diff --git a/adafruit_logging.py b/adafruit_logging.py index f1e171f..6394f16 100644 --- a/adafruit_logging.py +++ b/adafruit_logging.py @@ -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. @@ -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": @@ -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. @@ -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) diff --git a/examples/logging_simpletest.py b/examples/logging_simpletest.py index c8099a1..3bb25e1 100644 --- a/examples/logging_simpletest.py +++ b/examples/logging_simpletest.py @@ -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") @@ -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)