14

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?

alandalusi
  • 1,145
  • 4
  • 18
  • 39

3 Answers3

10

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

python script.py >> /logdir/script.py.log 2>&1
kaspernj
  • 1,243
  • 11
  • 16
10

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

Ahmed
  • 2,825
  • 1
  • 25
  • 39
  • 4
    Use `logger.exception('main crashed')`, which will print the stack trace too – Eric Dec 08 '17 at 19:39
  • Feel free to edit my answer to include logger.exception – Ahmed Dec 08 '17 at 22:05
  • 1
    Make sure, to setup the logging at some point. Python 3.9: `logger.basicConfig(filename=..., encoding='utf-8', level=logger.DEBUG)`. Also the library is called `logging`, not `logger`. (So for the upper code, you would need `import logging as logger`.) – PythoNic Feb 25 '21 at 08:40
  • 3.8 without parameter encoding, so `logger.basicConfig(filename=..., level=logger.DEBUG)`. See [Python docs for details (in your language :)](https://docs.python.org/3/howto/logging.html) – PythoNic Feb 25 '21 at 08:48
2

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

JeffAxe
  • 21
  • 2