diff --git a/adafruit_logging.py b/adafruit_logging/__init__.py similarity index 100% rename from adafruit_logging.py rename to adafruit_logging/__init__.py diff --git a/adafruit_logging/extensions.py b/adafruit_logging/extensions.py new file mode 100644 index 0000000..92b35b9 --- /dev/null +++ b/adafruit_logging/extensions.py @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: 2021 Alec Delaney for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +""" +`extensions` +==================================================== + +CircuitPython logging extension for logging to files + +* Author(s): Alec Delaney +""" + +from . import LoggingHandler + + +class FileHandler(LoggingHandler): + """File handler for working with log files off of the microcontroller (like + an SD card) + + :param filepath: The filepath to the log file + :param mode: Whether to write ('w') or append ('a'); default is to append + """ + + def __init__(self, filepath: str, mode: str = "a"): + self.logfile = open(filepath, mode, encoding="utf-8") + + def close(self): + """Closes the file""" + self.logfile.close() + + def format(self, level: int, msg: str): + """Generate a string to log + + :param level: The level of the message + :param msg: The message to format + """ + return super().format(level, msg) + "\r\n" + + def emit(self, level: int, msg: str): + """Generate the message and write it to the UART. + + :param level: The level of the message + :param msg: The message to log + """ + self.logfile.write(self.format(level, msg)) diff --git a/examples/logging_filehandler.py b/examples/logging_filehandler.py new file mode 100644 index 0000000..37e5de6 --- /dev/null +++ b/examples/logging_filehandler.py @@ -0,0 +1,30 @@ +# SPDX-FileCopyrightText: 2021 Alec Delaney +# SPDX-License-Identifier: MIT + +import board +import busio +from digitalio import DigitalInOut +import storage +import adafruit_sdcard +import adafruit_logging as logging +from adafruit_logging.extensions import FileHandler + +# Get chip select pin depending on the board, this one is for the Feather M4 Express +sd_cs = board.D10 + +# Set up an SD card to write to +spi = busio.SPI(board.SCK, board.MOSI, board.MISO) +cs = DigitalInOut(sd_cs) +sdcard = adafruit_sdcard.SDCard(spi, cs) +vfs = storage.VfsFat(sdcard) +storage.mount(vfs, "/sd") + +# Initialize log functionality +log_filepath = "/sd/testlog.log" +logger = logging.getLogger("testlog") +file_handler = FileHandler(log_filepath) +logger.addHandler(file_handler) +logger.setLevel(logging.INFO) + +logger.info("Logger initialized!") +logger.debug("You can even add debug statements to the log!")