Log Micropython console text to file

Here is a small snippet, how you can write everything what you get on console to file in your Micropython device. This may help you to debug long running devices.

import io, os
 
class logToFile(io.IOBase):
    def __init__(self):
        pass
 
    def write(self, data):
        with open("logfile.txt", mode="a") as f:
            f.write(data)
        return len(data)
 
# now your console text output is saved into file
os.dupterm(logToFile())
 
# disable logging to file
os.dupterm(None)