code.py
1 # SPDX-FileCopyrightText: 2018 Dave Astels for Adafruit Industries 2 # 3 # SPDX-License-Identifier: MIT 4 5 """ 6 UART based message handler for CircuitPython logging. 7 8 Adafruit invests time and resources providing this open source code. 9 Please support Adafruit and open source hardware by purchasing 10 products from Adafruit! 11 12 Written by Dave Astels for Adafruit Industries 13 Copyright (c) 2018 Adafruit Industries 14 Licensed under the MIT license. 15 16 All text above must be included in any redistribution. 17 """ 18 19 20 # Example: 21 # 22 # import board 23 # import busio 24 # from uart_handler import UartHandler 25 # import adafruit_logging as logging 26 # 27 # uart = busio.UART(board.TX, board.RX, baudrate=115200) 28 # logger = logging.getLogger('uart') 29 # logger.addHandler(UartHandler(uart)) 30 # logger.level = logging.INFO 31 # logger.info('testing') 32 33 from adafruit_logging import Handler 34 35 class UartHandler(Handler): 36 """Send logging output to a serial port.""" 37 38 def __init__(self, uart): 39 """Create an instance. 40 41 :param uart: the busio.UART instance to which to write messages 42 """ 43 self._uart = uart 44 45 def format(self, record): 46 """Generate a string to log. 47 48 :param record: The record (message object) to be logged 49 """ 50 return super().format(record) + '\r\n' 51 52 def emit(self, record): 53 """Generate the message and write it to the UART. 54 55 :param record: The record (message object) to be logged 56 """ 57 self._uart.write(bytes(self.format(record), 'utf-8'))