Skip to content

Commit 5329ef5

Browse files
pi-anldpgeorge
authored andcommitted
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 <[email protected]>
1 parent 028a369 commit 5329ef5

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

python-stdlib/logging/logging.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from micropython import const
2-
2+
import io
33
import sys
44
import time
55

@@ -148,10 +148,17 @@ def error(self, msg, *args):
148148
def critical(self, msg, *args):
149149
self.log(CRITICAL, msg, *args)
150150

151-
def exception(self, msg, *args):
151+
def exception(self, msg, *args, exc_info=True):
152152
self.log(ERROR, msg, *args)
153-
if hasattr(sys, "exc_info"):
154-
sys.print_exception(sys.exc_info()[1], _stream)
153+
tb = None
154+
if isinstance(exc_info, BaseException):
155+
tb = exc_info
156+
elif hasattr(sys, "exc_info"):
157+
tb = sys.exc_info()[1]
158+
if tb:
159+
buf = io.StringIO()
160+
sys.print_exception(tb, buf)
161+
self.log(ERROR, buf.getvalue())
155162

156163
def addHandler(self, handler):
157164
self.handlers.append(handler)

0 commit comments

Comments
 (0)