Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python logging close and application exit

Tags:

python

logging

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.

like image 498
Gregory Kuhn Avatar asked Jul 29 '15 13:07

Gregory Kuhn


People also ask

What are the five levels of logging in Python?

Log messages can have 5 levels - DEBUG, INGO, WARNING, ERROR and CRITICAL. They can also include traceback information for exceptions.

How do I close a log file?

If the Log file name box already displays a file name, you can click Close Open Log File to close the file.

What does logging getLogger (__ Name __) do?

getLogger(__name__) in multiple modules. Save this question. Show activity on this post. This means that logger names track the package/module hierarchy, and it's intuitively obvious where events are logged just from the logger name.


1 Answers

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()
like image 132
Wolph Avatar answered Oct 06 '22 09:10

Wolph