python logging close and application exit

2019-06-25 11:32发布

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.

For example:

logger = logging.getLogger('my_app')
logger.fatal("We're toast!")

the fatal method (or some such) would then:

  1. log the message as normal
  2. logging.shutdown()
  3. Call sys.exit(1)

Thoughts? Does something like this exist? Is this a bad idea?

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.

1条回答
叼着烟拽天下
2楼-- · 2019-06-25 11:49

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

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()
查看更多
登录 后发表回答