user2961127
user2961127

Reputation: 1143

How to write exceptions traceback to a file using python

Currently, my code gives traceback exception in console as per my expectations. I want to write exceptions to a file but code is not writing any exceptions to the file. A file is created but it is blank.

except Exception as error:
    print(traceback.print_exc())
    f = open('ErrorFile.txt', 'w')
    f.write(traceback.print_exc())
    f.close()

Upvotes: 1

Views: 1347

Answers (1)

Selcuk
Selcuk

Reputation: 59229

print_exc() does not return the traceback as a string. Instead it prints it directly. From the documentation:

traceback.print_exc([limit[, file]])

This is a shorthand for print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file). (In fact, it uses sys.exc_info() to retrieve the same information in a thread-safe way instead of using the deprecated variables.)

Therefore you should use:

traceback.print_exc(file=f)

Upvotes: 1

Related Questions