|
""" |
|
File based message handler for CircuitPython logging. |
|
|
|
Adafruit invests time and resources providing this open source code. |
|
Please support Adafruit and open source hardware by purchasing |
|
products from Adafruit! |
|
|
|
Written by Dave Astels for Adafruit Industries |
|
Copyright (c) 2018 Adafruit Industries |
|
Licensed under the MIT license. |
|
|
|
All text above must be included in any redistribution. |
|
""" |
|
|
|
#pylint:disable=missing-super-argument |
|
|
|
# Example: |
|
# |
|
# |
|
# from file_handler import FileHandler |
|
# import adafruit_logging as logging |
|
# l = logging.getLogger('file') |
|
# l.addHandler(FileHandler('log.txt')) |
|
# l.level = logging.ERROR |
|
# l.error("test") |
|
|
|
from adafruit_logging import LoggingHandler |
|
from adafruit_circuitplayground.express import cpx |
|
import time |
|
|
|
class FileHandler(LoggingHandler): |
|
|
|
def __init__(self, filename): |
|
"""Create an instance. |
|
|
|
:param filename: the name of the file to which to write messages |
|
|
|
""" |
|
self._filename = filename |
|
self._log_buffer = [] |
|
# Clear the file and add the header |
|
with open(filename, 'w') as f: |
|
f.write("Time (s), Current (mA)\n") |
|
|
|
def format(self, level, msg): |
|
"""Generate a string to log. |
|
|
|
:param level: The level at which to log |
|
:param msg: The core message |
|
|
|
""" |
|
return str(time.monotonic()) + "," + str(msg) + "\n" |
|
|
|
def emit(self, level, msg): |
|
"""Generate the message and write it to the File. |
|
|
|
:param level: The level at which to log |
|
:param msg: The core message |
|
|
|
""" |
|
if len(self._log_buffer) == 10: |
|
try: |
|
with open(self._filename, 'a') as f: |
|
while len(self._log_buffer) > 0: |
|
f.write(self._log_buffer.pop(0)) |
|
except OSError as e: |
|
# set NeoPixel 1 off and blink NeoPixel 0 (status) depending on |
|
# the OS error |
|
cpx.pixels[1] = (0, 0, 0) # Blank NeoPixel 1 |
|
message_color = (99, 0, 0) # Red for generic problem |
|
if e.args[0] == 28: # Device out of space |
|
message_color = (228, 160, 40) # set to Orange |
|
elif e.args[0] == 30: # Device is read only |
|
message_color = (181, 90, 0) # set to Yellow |
|
for x in range(1, 10): # Flash message 10 seconds |
|
cpx.pixels[0] = message_color |
|
time.sleep(1) |
|
cpx.pixels[0] = (0, 0, 0) |
|
time.sleep(1) |
|
else: |
|
self._log_buffer.append(self.format(level, msg)) |