7

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.

2
  • If it's just two-three lines, just write a small function for it? Commented Jul 29, 2015 at 13:16
  • @Stiffo Yup I'd say I'll probably have to do that alright. I was just wondering if there was something I was missing... it seems like quite an intuitive method to have. Commented Jul 29, 2015 at 13:18

1 Answer 1

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

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.