A file based handler is similar to the serial port handler, although the output is to a file either on flash (CIRCUITPY drive) or an SD card. If yo an SD card, the SPI bus must be set up to the card interface and the filesystem set.
The handler code is shown below (now part of the logging module):
class FileHandler(StreamHandler): """File handler for working with log files off of the microcontroller (like an SD card) :param str filename: The filename of the log file :param str mode: Whether to write ('w') or append ('a'); default is to append """ def __init__(self, filename: str, mode: str = "a") -> None: # pylint: disable=consider-using-with super().__init__(open(filename, mode=mode)) def close(self) -> None: """Closes the file""" self.stream.flush() self.stream.close() def format(self, record: LogRecord) -> str: """Generate a string to log :param record: The record (message object) to be logged """ return super().format(record) + "\r\n" def emit(self, record: LogRecord) -> None: """Generate the message and write it to the UART. :param record: The record (message object) to be logged """ self.stream.write(self.format(record))
You will need to do some extra work to enable your code to write to the file system. The details are covered in this guide.
Once that's done, you can direct log messages to a file, for example:
from file_handler import FileHandler import adafruit_logging as logging l = logging.getLogger('test') l.addHandler(FileHandler('log.txt')) l.setLevel(logging.ERROR) l.error("test")
This will result in a file log.txt on the CIRCUITPY drive containing something like:
1567.13: ERROR - test
Text editor powered by tinymce.