Skip to content

Commit

Permalink
Merge pull request #22 from tekktrik/feature/add-file-handler
Browse files Browse the repository at this point in the history
Add FileHandler class
  • Loading branch information
gamblor21 authored Nov 1, 2021
2 parents b868341 + e583c86 commit 8c24793
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
File renamed without changes.
46 changes: 46 additions & 0 deletions adafruit_logging/extensions.py
Original file line number Diff line number Diff line change
@@ -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))
30 changes: 30 additions & 0 deletions examples/logging_filehandler.py
Original file line number Diff line number Diff line change
@@ -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!")

0 comments on commit 8c24793

Please sign in to comment.