Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log a Python crash?

Tags:

python

I am running a python code in a raspberry Pi. The code is supposed to last forever. However, after a few hours it crashes. Since it is running on a remote machine, I cannot see the message it gives during the crash.

How can I store this message on a file so I can see what was the problem? is this does autonomously in linux? or should I write some function to export the error during crash. How can I do that?

like image 379
alandalusi Avatar asked Feb 27 '13 11:02

alandalusi


3 Answers

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

python script.py >> /logdir/script.py.log 2>&1
like image 197
kaspernj Avatar answered Sep 22 '22 12:09

kaspernj


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

like image 20
Ahmed Avatar answered Sep 21 '22 12:09

Ahmed


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

like image 32
JeffAxe Avatar answered Sep 19 '22 12:09

JeffAxe