Log to UART

With most devboards using the USB connection for the REPL or direct control, you may want to have a secondary USB (or serial) connection - to the same computer or maybe another one. You can also of course use a UART wireless link, XBee, etc. UART is pretty common!

The following code demonstrates logging messages to a board serial (UART) port (usually pin TX):

"""
UART 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:
#
# import board
# import busio
# from uart_handler import UartHandler
# import adafruit_logging as logging
#
# uart = busio.UART(board.TX, board.RX, baudrate=115200)
# logger = logging.getLogger('uart')
# logger.addHandler(UartHandler(uart))
# logger.level = logging.INFO
# logger.info('testing')

from adafruit_logging import LoggingHandler

class UartHandler(LoggingHandler):
    """Send logging output to a serial port."""

    def __init__(self, uart):
        """Create an instance.

        :param uart: the busio.UART instance to which to write messages

        """
        self._uart = uart

    def format(self, level, msg):
        """Generate a string to log.

        :param level: The level at which to log
        :param msg: The core message

        """
        return super().format(level, msg) + '\r\n'

    def emit(self, level, msg):
        """Generate the message and write it to the UART.

        :param level: The level at which to log
        :param msg: The core message

        """
        self._uart.write(bytes(self.format(level, msg), 'utf-8'))

This does a few things. 

First, it uses the UART instance passed in, giving you the flexibility to use the serial port you want.

It provides its own format method which calls the superclass's format to build the output string (that's the LoggingHandler class) and appends a newline sequence (a carriage return then a line feed) since write doesn't automatically terminate the line the way print does.

The emit method uses format to build the string, converts it to a bytearray and writes the bytes to the UART.

You would use it like in the following example:

Download: file
import board
import busio
from uart_handler import UartHandler
import adafruit_logging as logging

uart = busio.UART(board.TX, board.RX, baudrate=115200)
logger = logging.getLogger('test')
logger.addHandler(UartHandler(uart))
logger.setLevel(logging.INFO)
logger.info('testing')
This guide was first published on Mar 18, 2019. It was last updated on Mar 18, 2019. This page (Log to UART) was last updated on Sep 21, 2019.