Logging Stacktrace To File

Peter Otten __peter__ at web.de
Tue Apr 13 09:10:32 EDT 2004


Olaf Meding wrote:

>> ... have to catch the exception and then log it to the file.
> 
> Right.  I do also know how to open a file and write to it.
> 
> But how do I get at the stack trace?  I would like to have it look the
> same in the file as what gets printed to the screen.

A quick and dirty approach to deal with _uncaught_ exceptions (untested):

>>> def eh(klass, inst, tb):
...     sys.stderr = file("tmp.txt", "a")
...     sys.__excepthook__(klass, inst, tb)
...     sys.stderr.close()
...     sys.stderr = sys.__stderr__
...
>>> import sys
>>> raise Exception("so what")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
Exception: so what
>>> sys.excepthook = eh
>>> raise Exception("so what")
>>>
$ cat tmp.txt
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
Exception: so what

Peter



More information about the Python-list mailing list