sys.exc_info() into string

Chris Liechti cliechti at gmx.net
Sun Jun 23 17:20:22 EDT 2002


Magnus <spammers.do.not.bother at void.bogus> wrote in 
news:moqR8.44823$n4.10512288 at newsc.telia.net:

> Chris Liechti wrote:
> 
>> Magnus <spammers.do.not.bother at void.bogus> wrote in
>> news:KZoR8.44805$n4.10504231 at newsc.telia.net:
>>> in my program I am catching exceptions that I might have missed by
>>> using something like:
>>> 
>>> try:
>>>         doMyStuff()
>>> except:
>>>         type = sys.exc_info()[0]
>>>         syslog.syslog(syslog.LOG_EMERG, "My program: unexpected error"
>>>         + type)
>>> 
>>> The thing is that I can not figure out how to make "type" into a
>>> string above so I can use it for e.g. syslog(). Is there an easy way
>>> of doing this?
>> 
>> yes, the traceback module has functions to format an exception as string
>> or to print.
>> 
>> format_exc is a candidate for you. it return a list of lines from which
>> you can select to mosr informative or just join it the one big string.
>> 
>> chris
>> 
> 
> I think following is working...
> 
> except:
>         syslog.syslog(syslog.LOG_EMERG, "My program: unexpected er
> ror" + str(sys.exc_info()[0]))
> 
> ...thanks for the suggestion.

i encourage you to include the linenumber and file in the message too. when 
you want to fix the error, you don't have to try to reproduce it, which 
could be very tricky.
and it will be frustrating for you to see that your programm has errors, 
but you can't fix them because you don't know where they occured...

>>> try:
... 	e
... except:
... 	print ''.join(traceback.format_exception(
...                *sys.exc_info())[-2:]).strip().replace('\n',': ')
... 
File "<interactive input>", line 2, in ?: NameError: name 'e' is not 
defined

strip and replace are used to make one line of it. of course you could also 
print the entire traceback to the log.

chris

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list