Capture and save the traceback from error



  • I'm using my LoPys (lopy4) far away from my home, it means that if they have an error I can't go in a few days to see what's happening. Actually these days I'm having an error that I don't know what's happening.

    My question is, can I save in a txt file the traceback info? This is very interesting because I will know the file and line where the error happened and I don't need to be in real time watching the console.

    Actually I'm using the reset info, machine.reset_cause(), but is not enough.

    I thought using try/except but with this I can capture the exception, but not the callback. Furthermore I'm not sure I'm doing correctly because I have a try/except at the start of each file and this can't be optimum. Like

    # main.py
    try:
        # All my "main.py" code.
    except Exception as e:
        print(e) # Now I'm printing but I will write a txt file
    
    # myClock.py
    try:
        class Clock:
    
            def __init__(self):
                # Code
    
            def func1(self):
                # Code
    
    except Exception as e:
        print(e)
    

    You know how to do this like a pro?

    Thank you very much!



  • @M-m I put mine in a function def logtraceback(e): which I call from any Exception as e: where I want to log the traceback.



  • @kjm First of all, thank you very much for answering. I'm happy to see that I was in the correct way, but now my question is, where I have to put this code? In my main? In each function? In each class?



  • except Exception as e:
      sys.print_exception(e)                                                    # see the traceback
      from uio import StringIO; s=StringIO(); sys.print_exception(e, s)         # puts traceback into variable s, does not actually print
      s=s.getvalue(); s.replace('"',"").replace("'",'')                         # remove quotes that might confuse error logging via https
    

    after this bit of massaging s is a sting you can save to a file. As provided to me by robert-hh (knowledgeable forum stalwart) a year or so ago when I was a python newbie.



Pycom on Twitter