logger.exception
期间如何调用__exit__
?
我的上下文管理器类定义是:
import logging
from types import TracebackType
from typing import Optional, Type
class B(A):
def __init__(self):
super().__init__()
self.log = logging.getLogger("B")
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_inst: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> bool:
if exc_inst is not None:
self.log.exception("EXCEPTION!")
return False # let exception propagate
return True
我是否需要显式地将参数传递给
self.log.exception
,以便它打印异常信息和回溯?
不,您不必显式地将异常详细信息传递给
log.exception
,它会自动拾取它们。
logger.exception
不需要特殊参数;只需拨打self.log.exception("EXCEPTION!")
即可。
import logging
from types import TracebackType
from typing import Optional, Type
class B:
def __init__(self):
super().__init__()
self.log = logging.getLogger("B")
self.log.info("Init B")
def __enter__(self):
self.log.info("Entering B")
return self
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_inst: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> bool:
self.log.info("Exiting B")
if exc_inst is not None:
self.log.exception("EXCEPTION!")
# return False # let exception propagate
return True
def main():
with B() as _:
print("no exception")
with B() as _:
raise RuntimeError("BLARG!!!!!")
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
main()
打印
INFO:B:Init B
INFO:B:Entering B
no exception
INFO:B:Exiting B
INFO:B:Init B
INFO:B:Entering B
INFO:B:Exiting B
ERROR:B:EXCEPTION!
Traceback (most recent call last):
File ".\try1.py", line 34, in main
raise RuntimeError("BLARG!!!!!")
RuntimeError: BLARG!!!!!
如果
return False
从 __exit__
发生,则外部异常处理程序可能会再次打印异常。