Skip to content

Commit 01f33e9

Browse files
authored
Merge pull request #45 from vladak/mqtt_handler_example
add MQTT handler example
2 parents ebf01e1 + da73359 commit 01f33e9

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

examples/logging_mqtt_handler.py

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# SPDX-FileCopyrightText: 2022 vladak
2+
# SPDX-License-Identifier: Unlicense
3+
"""
4+
Demonstrate how to use a single logger to emit log records to
5+
both console and MQTT broker, in this case Adafruit IO.
6+
"""
7+
8+
import json
9+
import socket
10+
import ssl
11+
12+
import adafruit_minimqtt.adafruit_minimqtt as MQTT
13+
14+
import adafruit_logging as logging
15+
16+
# adafruit_logging defines log levels dynamically.
17+
# pylint: disable=no-name-in-module
18+
from adafruit_logging import NOTSET, Handler, LogRecord
19+
20+
21+
class MQTTHandler(Handler):
22+
"""
23+
Log handler that emits log records as MQTT PUBLISH messages.
24+
"""
25+
26+
def __init__(self, mqtt_client: MQTT.MQTT, topic: str) -> None:
27+
"""
28+
Assumes that the MQTT client object is already connected.
29+
"""
30+
super().__init__()
31+
32+
self._mqtt_client = mqtt_client
33+
self._topic = topic
34+
35+
# To make it work also in CPython.
36+
self.level = NOTSET
37+
38+
def emit(self, record: LogRecord) -> None:
39+
"""
40+
Publish message from the LogRecord to the MQTT broker, if connected.
41+
"""
42+
try:
43+
if self._mqtt_client.is_connected():
44+
self._mqtt_client.publish(self._topic, record.msg)
45+
except MQTT.MMQTTException:
46+
pass
47+
48+
# To make this work also in CPython's logging.
49+
def handle(self, record: LogRecord) -> None:
50+
"""
51+
Handle the log record. Here, it means just emit.
52+
"""
53+
self.emit(record)
54+
55+
56+
def main():
57+
"""
58+
Demonstrate how to use MQTT log handler.
59+
"""
60+
logger = logging.getLogger(__name__)
61+
62+
broker = "io.adafruit.com"
63+
port = 8883
64+
username = "Adafruit_IO_username"
65+
password = "Adafruit_IO_key"
66+
feedname = "Adafruit_feed_name"
67+
mqtt_topic = f"{username}/feeds/{feedname}"
68+
mqtt_client = MQTT.MQTT(
69+
broker=broker,
70+
port=port,
71+
username=username,
72+
password=password,
73+
socket_pool=socket,
74+
ssl_context=ssl.create_default_context(),
75+
)
76+
mqtt_client.connect()
77+
mqtt_handler = MQTTHandler(mqtt_client, mqtt_topic)
78+
print("adding MQTT handler")
79+
logger.addHandler(mqtt_handler)
80+
81+
stream_handler = logging.StreamHandler()
82+
print("adding Stream handler")
83+
logger.addHandler(stream_handler)
84+
85+
data = "foo bar"
86+
print("logging begins !")
87+
# This should emit both to the console as well as to the MQTT broker.
88+
logger.warning(json.dumps(data))
89+
90+
91+
if __name__ == "__main__":
92+
main()

0 commit comments

Comments
 (0)