Question
How can I log my Python errors?
- try:
- do_something()
- except:
- # How can I log my exception here, complete with its traceback?
Use logging.exception from with an except: handler to log the current exception, prepended with a message.
- import logging
- LOG_FILENAME = '/tmp/logging_example.out'
- logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
- logging.debug('This message should go to the log file')
- try:
- run_my_stuff()
- except:
- logging.exception('Got exception on main handler')
- raise
- DEBUG:root:This message should go to the log file
- ERROR:root:Got exception on main handler
- Traceback (most recent call last):
- File "/tmp/teste.py", line 9, in
- run_my_stuff()
- NameError: name 'run_my_stuff' is not defined
沒有留言:
張貼留言