How to log a Python crash?

You can store the output in a file, if the process is started like this:

python script.py >> /logdir/script.py.log 2>&1

You can have a main function and log in case if main function crashes

def main():
   ...
   raise ValueError("crashed because I'm a bad exception")
   ...

if __name__ == "__main__":
   try:
      main()
   except Exception as e:
      logger.exception("main crashed. Error: %s", e)

This is better in case if you're using something like logstash and want to see the error and the time on your UI.

Thanks to Eric for improving the answer


I had tried many attempts myself, but they all seemed weird...Until I figured it out! Simply write this code around your python file, and all should be well! By the way, I will be naming the crashlogs CRASH- and then the python time (e.g. CRASH-1607012036.015824.txt)

try:
    <your program here>
except Exception as e:
    crash=["Error on line {}".format(sys.exc_info()[-1].tb_lineno),"\n",e]
    print(crash)
    timeX=str(time.time())
    with open("monstergame/crashlogs/CRASH-"+timeX+".txt","w") as crashLog:
        for i in crash:
            i=str(i)
            crashLog.write(i)

Note: This is Python 3 code, not Python 2

Tags:

Python