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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With