logging: Add full support for logging exception tracebacks.

This commit allows you to pass an exception object in as the exc_info kwarg
(CPython allows this), so logging exceptions can work even if the
MICROPY_PY_SYS_EXC_INFO option is disabled in the firmware.

Separately to that, currently even when sys.exc_info() is enabled, it's
only printing the traceback to _stream = sys.stderr - not to the configured
logging handlers.  This means for instance if you've got a file log
handler it misses out on the tracebacks.  That's also fixed in this commit.

Signed-off-by: Andrew Leech <andrew.leech@planetinnovation.com.au>
pull/660/head
Andrew Leech 2023-05-18 17:15:46 +10:00 zatwierdzone przez Damien George
rodzic 028a369f90
commit 5329ef5301
1 zmienionych plików z 11 dodań i 4 usunięć

Wyświetl plik

@ -1,5 +1,5 @@
from micropython import const
import io
import sys
import time
@ -148,10 +148,17 @@ class Logger:
def critical(self, msg, *args):
self.log(CRITICAL, msg, *args)
def exception(self, msg, *args):
def exception(self, msg, *args, exc_info=True):
self.log(ERROR, msg, *args)
if hasattr(sys, "exc_info"):
sys.print_exception(sys.exc_info()[1], _stream)
tb = None
if isinstance(exc_info, BaseException):
tb = exc_info
elif hasattr(sys, "exc_info"):
tb = sys.exc_info()[1]
if tb:
buf = io.StringIO()
sys.print_exception(tb, buf)
self.log(ERROR, buf.getvalue())
def addHandler(self, handler):
self.handlers.append(handler)