2017年8月24日 星期四

[ Python 常見問題 ] Log exception with traceback

Source From Here 
Question 
How can I log my Python errors? 
  1. try:  
  2.     do_something()  
  3. except:  
  4.     # How can I log my exception here, complete with its traceback?  
How-To 
Use logging.exception from with an except: handler to log the current exception, prepended with a message. 
  1. import logging  
  2. LOG_FILENAME = '/tmp/logging_example.out'  
  3. logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)  
  4.   
  5. logging.debug('This message should go to the log file')  
  6.   
  7. try:  
  8.     run_my_stuff()  
  9. except:  
  10.     logging.exception('Got exception on main handler')  
  11.     raise  
Now looking at the log file, /tmp/logging_example.out
  1. DEBUG:root:This message should go to the log file  
  2. ERROR:root:Got exception on main handler  
  3. Traceback (most recent call last):  
  4.   File "/tmp/teste.py", line 9, in   
  5.     run_my_stuff()  
  6. NameError: name 'run_my_stuff' is not defined  

沒有留言:

張貼留言

[Linux 常見問題] What's the best way to send a signal to all members of a process group?

Source From  Here   Question   I want to  kill a whole process tree.  What is the best way to do this using any common scripting languages? ...