Skip to content

Commit 9fd0bc8

Browse files
committed
Merge branch 'tekktrik-feature/add-file-handler'
2 parents 4afdd43 + 7e9924b commit 9fd0bc8

File tree

3 files changed

+76
-0
lines changed

3 files changed

+76
-0
lines changed
File renamed without changes.

adafruit_logging/extensions.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# SPDX-FileCopyrightText: 2021 Alec Delaney for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
"""
6+
`extensions`
7+
====================================================
8+
9+
CircuitPython logging extension for logging to files
10+
11+
* Author(s): Alec Delaney
12+
"""
13+
14+
from . import LoggingHandler
15+
16+
17+
class FileHandler(LoggingHandler):
18+
"""File handler for working with log files off of the microcontroller (like
19+
an SD card)
20+
21+
:param filepath: The filepath to the log file
22+
:param mode: Whether to write ('w') or append ('a'); default is to append
23+
"""
24+
25+
def __init__(self, filepath: str, mode: str = "a"):
26+
self.logfile = open(filepath, mode, encoding="utf-8")
27+
28+
def close(self):
29+
"""Closes the file"""
30+
self.logfile.close()
31+
32+
def format(self, level: int, msg: str):
33+
"""Generate a string to log
34+
35+
:param level: The level of the message
36+
:param msg: The message to format
37+
"""
38+
return super().format(level, msg) + "\r\n"
39+
40+
def emit(self, level: int, msg: str):
41+
"""Generate the message and write it to the UART.
42+
43+
:param level: The level of the message
44+
:param msg: The message to log
45+
"""
46+
self.logfile.write(self.format(level, msg))

examples/logging_filehandler.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# SPDX-FileCopyrightText: 2021 Alec Delaney
2+
# SPDX-License-Identifier: MIT
3+
4+
import board
5+
import busio
6+
from digitalio import DigitalInOut
7+
import storage
8+
import adafruit_sdcard
9+
import adafruit_logging as logging
10+
from adafruit_logging.extensions import FileHandler
11+
12+
# Get chip select pin depending on the board, this one is for the Feather M4 Express
13+
sd_cs = board.D10
14+
15+
# Set up an SD card to write to
16+
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
17+
cs = DigitalInOut(sd_cs)
18+
sdcard = adafruit_sdcard.SDCard(spi, cs)
19+
vfs = storage.VfsFat(sdcard)
20+
storage.mount(vfs, "/sd")
21+
22+
# Initialize log functionality
23+
log_filepath = "/sd/testlog.log"
24+
logger = logging.getLogger("testlog")
25+
file_handler = FileHandler(log_filepath)
26+
logger.addHandler(file_handler)
27+
logger.setLevel(logging.INFO)
28+
29+
logger.info("Logger initialized!")
30+
logger.debug("You can even add debug statements to the log!")

0 commit comments

Comments
 (0)