Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

save Exceptions to file in python

I want to save all following Exceptions in a file. The reason why I need this is because the IDLE for python 3.1.1 in Ubuntu raises an Exception at calltipps, but close to fast, that it isn't readble. Also I need this for testing. The best, would be if I just call a function which saves all Exception to a file. Thank you! ;)

// edit:

i had looked first for a more general way! so that you do not have to place your whole code in a function or indentation. but now that worked wery well for me. although I would be still grateful, if you find a way!

thanks!

like image 308
Joschua Avatar asked Nov 11 '09 21:11

Joschua


1 Answers

If you have a convenient main() function (whatever it's called), then you can use the logging module:

import logging

def main():
    raise Exception("Hey!")

logging.basicConfig(level=logging.DEBUG, filename='/tmp/myapp.log')

try:
    main()
except:
    logging.exception("Oops:")

logging.exception conveniently gets the current exception and puts the details in the log:

ERROR:root:Oops:
Traceback (most recent call last):
  File "C:\foo\foo.py", line 9, in <module>
    main()
  File "C:\foo\foo.py", line 4, in main
    raise Exception("Hey!")
Exception: Hey!
like image 147
Ned Batchelder Avatar answered Oct 07 '22 15:10

Ned Batchelder