Python: sys.excepthook and logging uncaught exceptions across multiple modules

旧城冷巷雨未停 提交于 2019-12-12 01:09:40

问题


In all of my Python main scripts and modules, I have been trying to implement a way to log uncaught exceptions to the module in which the exception was thrown's logger. I'm doing this the same way in all of my files:

def log_unhandled_exception(*exc_info):
   text = "".join(traceback.format_exception(*exc_info))
   logger.critical("An unhandled exception has caused this script to terminate prematurely.  Here are the details: {0}".format(text))
   sys.exit(2)

def some_function():
   # ... 

sys.excepthook = log_unhandled_exception
logger = logging.getLogger("Module1") # or "Module2", "Module3", etc., each module has it's own logger

When I run into an uncaught exception, I sometimes don't get the intended logger. I think it has to do with the ordering that I import the modules: if I import module1 then import module2, and then call a function in module2 and run into an exception, it seems I get module1's logger. Conversely if I reverse the order of imports (module2 comes before module1), and I attempt the same test (exception thrown in module2), I correctly get module2's logger. I would have thought the LATER import would take precedence (overwrite the former's sys.excepthook reference), but no.

I was able to solve this problem (I guess...) by giving each logger reference a unique name in each module. So to amend the code above, THIS pattern works without regard to the order of module imports:

def log_unhandled_exception(*exc_info):
   text = "".join(traceback.format_exception(*exc_info))
   module1_logger.critical("An unhandled exception has caused this script to terminate prematurely.  Here are the details: {0}".format(text))
   sys.exit(2)

def some_function():
   # ... 

sys.excepthook = log_unhandled_exception
module1_logger = logging.getLogger("Module1") # or "Module2", "Module3", etc., each module has it's own logger

Is this the proper way to achieve my desired goal, which is for every module to have it's own logger, and every module to use it's logger to log uncaught exceptions.

(The actual code is more varied, and has a reason for every module to have their own implementation of log_unhandled_exception())


回答1:


sys.excepthook is global for your Python process. The last value that you set to it wins. Using unique names in different files for module loggers won't have any effect on it.



来源:https://stackoverflow.com/questions/20714644/python-sys-excepthook-and-logging-uncaught-exceptions-across-multiple-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!