Skip to content

Instantly share code, notes, and snippets.

@wsw70 wsw70/mqtt-log.py
Created Sep 15, 2018

Embed
What would you like to do?
Example of a service which logs all messages sent to a MQTT broker
import paho.mqtt.client as mqtt
import logbook
import os
import sys
def on_connect(client, userdata, flags, rc):
if rc:
log.critical(f"failed to connect to {mqtt_server}, error code is {rc}. Aborting.")
sys.exit()
else:
log.info(f"connected to {mqtt_server}")
client.subscribe("#")
log.info(f"subscribed to # (all topics)")
def on_message(client, userdata, msg):
log.info(f"{msg.topic} {msg.payload.decode()}")
# log to console
logbook.StreamHandler(sys.stdout).push_application()
log = logbook.Logger('log-mqtt')
log.level = logbook.DEBUG if os.environ.get('DEV') else logbook.INFO
mqtt_server = "mqtt.example.com"
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(mqtt_server, 1883, 60)
log.info(f"starting MQTT loop")
client.loop_forever()
[Unit]
Description=MQTT full logger
[Service]
Type=simple
ExecStart=/root/mqtt-log/log-mqtt.py
Restart=on-failure
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.