python日志关闭和应用程序退出 [英] python logging close and application exit
问题描述
我正在应用程序中使用日志记录模块,但我发现,如果日志记录模块支持一种可以优雅地关闭文件句柄等然后关闭应用程序的方法,那将是一件很不错的事情.
I am using the logging module in an application and it occurred to me that it would be neat if the logging module supported a method which would gracefully close file handles etc and then close the application.
例如:
logger = logging.getLogger('my_app')
logger.fatal("We're toast!")
致命方法(或某些类似方法)将:
the fatal method (or some such) would then:
- 正常记录消息
- logging.shutdown()
- 致电sys.exit(1)
有什么想法吗? 是否存在这样的东西? 这是一个坏主意吗?
Thoughts? Does something like this exist? Is this a bad idea?
我为什么要这个? 嗯,我的代码中有些地方我希望应用程序死掉,而不断重复执行 2 和 3 似乎很浪费.
Why do I want this? Well there are a few places in my code where I want the app to die and it seems a waste to keep repeating the code to do 2 and 3.
推荐答案
也许不是最干净的解决方案,但这浮现在脑海:
Perhaps not the cleanest solution, but this springs to mind:
try:
# Your main function
main()
except:
logger.exception('some message')
sys.exit(1)
然后在实际代码中引发任何异常
And in the actual code just raise any exception
尽管这将为您提供一个不同的记录器.如果只是关闭部分,只需使用try/finally:
Although that will give you a different logger. If it's just about the shutdown part, just use try/finally:
try:
# do whatever here
main()
finally:
logging.shutdown()
这篇关于python日志关闭和应用程序退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!