muutils.logger.exception_context
1import json 2 3from muutils.json_serialize import json_serialize 4 5 6class ExceptionContext: 7 """context manager which catches all exceptions happening while the context is open, `.write()` the exception trace to the given stream, and then raises the exception 8 9 10 for example: 11 12 ```python 13 errorfile = open('error.log', 'w') 14 15 with ExceptionContext(errorfile): 16 # do something that might throw an exception 17 # if it does, the exception trace will be written to errorfile 18 # and then the exception will be raised 19 ``` 20 21 """ 22 23 def __init__(self, stream): 24 self.stream = stream 25 26 def __enter__(self): 27 return self 28 29 def __exit__(self, exc_type, exc_value, exc_traceback): 30 if exc_type is not None: 31 self.stream.write( 32 json.dumps( 33 json_serialize( 34 { 35 "exc_type": exc_type, 36 "exc_value": exc_value, 37 "exc_traceback": exc_traceback, 38 } 39 ) 40 ) 41 ) 42 return False 43 return True
class
ExceptionContext:
7class ExceptionContext: 8 """context manager which catches all exceptions happening while the context is open, `.write()` the exception trace to the given stream, and then raises the exception 9 10 11 for example: 12 13 ```python 14 errorfile = open('error.log', 'w') 15 16 with ExceptionContext(errorfile): 17 # do something that might throw an exception 18 # if it does, the exception trace will be written to errorfile 19 # and then the exception will be raised 20 ``` 21 22 """ 23 24 def __init__(self, stream): 25 self.stream = stream 26 27 def __enter__(self): 28 return self 29 30 def __exit__(self, exc_type, exc_value, exc_traceback): 31 if exc_type is not None: 32 self.stream.write( 33 json.dumps( 34 json_serialize( 35 { 36 "exc_type": exc_type, 37 "exc_value": exc_value, 38 "exc_traceback": exc_traceback, 39 } 40 ) 41 ) 42 ) 43 return False 44 return True
context manager which catches all exceptions happening while the context is open, .write()
the exception trace to the given stream, and then raises the exception
for example:
errorfile = open('error.log', 'w')
with ExceptionContext(errorfile):
# do something that might throw an exception
# if it does, the exception trace will be written to errorfile
# and then the exception will be raised