I'd like to log to a file the traceback of any error in the exact same form as the standard Python traceback display, plus the datetime.
This nearly works:
import sys, traceback, time
def exc_handler(ex_cls, ex, tb):
with open('mylog.log', 'a') as f:
dt = time.strftime('%Y-%m-%d %H:%M:%S')
f.write(f"{dt}\n")
traceback.print_tb(tb, file=f)
# traceback.print_exception(ex, tb=None, value="", file=f) # another approach, doesn't work either
f.write(f"{dt}\n")
sys.excepthook = exc_handler
def function1():
1/0
def function2():
function1()
function2()
except that the exception name is not displayed, and other similar little differences ("Traceback..." is not written).
How to have the exact same format as the default Python exception traceback display?
Example:
2022-10-19 11:19:18
File "D:\main.py", line 18, in <module>
function2()
File "D:\main.py", line 16, in function2
function1()
File "D:\main.py", line 13, in function1
1/0
2022-10-19 11:19:18
Here is how it should be logged:
2022-10-19 11:19:18
Traceback (most recent call last):
File "D:\main.py", line 18, in <module>
function2()
File "D:\main.py", line 16, in function2
function1()
File "D:\main.py", line 13, in function1
1/0
ZeroDivisionError: division by zero
2022-10-19 11:19:18
Notes:
if possible, I don't want to include my whole code in a global big
try: except:
block, I prefer an exception handler on top, and then the usual code without a bigtry: except:
block.I've already read How to log error to file, and not fail on exception and similar questions, but here it's not the exact same display as usual traceback display