Record traceback into log file (Custom Exception)

Viewed 55

I would like to record the Traceback of my custom Exception. For example:

main.py:

from error import *
x=int(input("guess a number"))
y=10
if x==y:
    print("corret")
else:
    raise wrong()

error.py:

from datetime import datetime
import os
import logging
class ErrorHandler:
         def log_info(self):
            try:
                os.makedirs('Error Log')
            except OSError:
                pass
            current_datetime = datetime.now()
            current_datetime = current_datetime.strftime("%Y%m%d")
            logging.basicConfig(filename=r"Error log\Errorlog_" + current_datetime + ".log", level=logging.DEBUG)

class wrong(Exception):
        def __init__(self):
            print('wrong')
            current_datetime = datetime.now()
            current_datetime = current_datetime.strftime("%Y%m%d_%H:%M:%S")
            ErrorHandler().log_info()
            logging.exception(current_datetime, exc_info=True)

What I get inside the log is this:

ERROR:root:20210414_11:16:37
NoneType: None

Is there anyway I can record the Traceback into log file?

1 Answers

I log my tracebacks with this approach

import traceback

try:
    #trigger Exception
    int("abc")
except:
    #write full traceback to a file, relative to the script
    f = open("error_log.txt", "w")
    f.write(traceback.format_exc())
    f.close()

The created log file will contain the following info:

Traceback (most recent call last):
  File "D:\Path\to\script.py", line 8, in <module>
    int("abc")
ValueError: invalid literal for int() with base 10: 'abc'
Related