@@ -202,6 +202,15 @@ def __init__(self, stream: Optional[WriteableStream] = None) -> None:
202
202
self .stream = stream
203
203
"""The stream to log to"""
204
204
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
+
205
214
def emit (self , record : LogRecord ) -> None :
206
215
"""Send a message to the console.
207
216
@@ -224,6 +233,8 @@ class FileHandler(StreamHandler):
224
233
:param str mode: Whether to write ('w') or append ('a'); default is to append
225
234
"""
226
235
236
+ terminator = "\r \n "
237
+
227
238
def __init__ (self , filename : str , mode : str = "a" ) -> None :
228
239
# pylint: disable=consider-using-with
229
240
if mode == "r" :
@@ -235,13 +246,6 @@ def close(self) -> None:
235
246
self .stream .flush ()
236
247
self .stream .close ()
237
248
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
-
245
249
def emit (self , record : LogRecord ) -> None :
246
250
"""Generate the message and write it to the file.
247
251
@@ -538,3 +542,27 @@ def critical(self, msg: str, *args) -> None:
538
542
can be empty
539
543
"""
540
544
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 )
0 commit comments