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):
    def write(self, data):
        with open("logfile.txt", mode="a") as f:
        return len(data)
# now your console text output is saved into file
# disable logging to file
Martin Ortiz, 2021/08/01 13:23

hi, I tried and worked perfect. but i would like to understand how as I need to make some changes on it, for instead be sure to flush the file when/before to reboot/deepsleep-.

Also I would like to name the file adding a _YYMMDDHHMMSS ending, or just pass a name as a additional parameter.

I was reading about io.IOBase for an ESP32 and at

any hint?

Ignas, 2021/08/16 14:03, 2021/09/06 19:23

You may give filename custom name based on date via following name:

    def write(self, data):
        logFileName = 'info_{}.log'.format(strftime('%d_%m_%Y_%T'))
        with open(logFileName, mode="a") as f:
        return len(data)

You may use all date and time variable (google strftime function ), just avoid slashes and backslashes, semicolon and other special symbols in file name.

Enter your comment. Wiki syntax is allowed:
If you can't read the letters on the image, download this .wav file to get them read to you.
  • blog/210105_log_micropython_console_text_to_file.txt
  • Last modified: 2021/11/19 18:17
  • by Ignas