Testing handlers

Here's a simple program to test it out a handler. This was used to created the log shown on the Overview page. This shows the Adafruit IO handler but you may change the handler to one of the others.

import time
import random
from aio_handler import AIOHandler
import adafruit_logging as logging

l = logging.getLogger('aio')

while True:
    t = random.randint(1, 5)
    if t == 1:
        l.debug("debug message: %d", random.randint(0, 1000))
    elif t == 2:
        l.info("debug message: %d", random.randint(0, 1000))
    elif t == 3:
        l.warning("warning message: %d", random.randint(0, 1000))
    elif t == 4:
        l.error("error message: %d", random.randint(0, 1000))
    elif t == 5:
        l.critical("critical message: %d", random.randint(0, 1000))
    time.sleep(5.0 + (random.random() * 5.0))

Getting More Elaborate

A single logger sends it's output to a single place (we've seen console, serial port, and a file), but there's nothing that says you can only have one logger in use. Perhaps you'll want everything logged to a file, and critical errors logged to the console as well.  Just create a file based logger and log everything with it, and also have a console logger (using the default PrintLogger) that you use for critical things.

You could even write a custom handler that takes other handlers and routes messages appropriately based on level. For example, logging most messages to a file, but sending critical ones via text or email, or sounding an alarm... it doesn't have to be just outputting strings.

This guide was first published on Mar 18, 2019. It was last updated on Feb 26, 2024.

This page (Testing and Expanding Handlers) was last updated on Mar 18, 2019.

Text editor powered by tinymce.