From f0b14a3c9f7b69cf5680ca828877bc736d17dca9 Mon Sep 17 00:00:00 2001 From: Michael Murton <6764025+CrazyIvan359@users.noreply.github.com> Date: Sun, 20 Dec 2020 20:37:41 -0500 Subject: [PATCH] mqtt use custom client logger --- CHANGELOG.md | 1 + mqttany/logger.py | 14 ++++++++++++-- mqttany/modules/mqtt.py | 31 ++++++++++++++++++++++++++++++- 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b1183d..db762fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ * **Changed** * LED restructure set/get pixel functions to simplify array subclassing. * LED some minor cleanup of array subtypes. + * MQTT use custom client logger for better control of log messages. * **Fixed** * Missing comma in Odroid C1+ and C2 board definitions. diff --git a/mqttany/logger.py b/mqttany/logger.py index a84396f..7e7bd5c 100644 --- a/mqttany/logger.py +++ b/mqttany/logger.py @@ -25,13 +25,23 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -__all__ = ["get_logger", "set_level", "log_traceback", "uninit"] +__all__ = [ + "get_logger", + "set_level", + "log_traceback", + "uninit", + "TRACE", + "DEBUG", + "INFO", + "WARN", + "ERROR", +] import os, sys, errno, inspect, traceback from types import MethodType import logging from logging import handlers -from logging import DEBUG, INFO, WARNING as WARN +from logging import DEBUG, INFO, WARNING as WARN, ERROR import colorlog TRACE = 5 # trace level logging diff --git a/mqttany/modules/mqtt.py b/mqttany/modules/mqtt.py index 8c9d0ba..b298d75 100644 --- a/mqttany/modules/mqtt.py +++ b/mqttany/modules/mqtt.py @@ -36,6 +36,17 @@ from common import BusMessage from modules import ModuleType +try: + from paho.mqtt.client import ( + MQTT_LOG_DEBUG, + MQTT_LOG_ERR, + MQTT_LOG_INFO, + MQTT_LOG_NOTICE, + MQTT_LOG_WARNING, + ) +except ModuleNotFoundError: + pass + _module_type = ModuleType.COMMUNICATION log = logger.get_logger() @@ -122,6 +133,24 @@ def load(config_raw): return False +def client_logger(): + + LEVEL_MAP = { + MQTT_LOG_INFO: logger.DEBUG, + MQTT_LOG_NOTICE: logger.DEBUG, + MQTT_LOG_WARNING: logger.WARN, + MQTT_LOG_ERR: logger.ERROR, + MQTT_LOG_DEBUG: logger.TRACE, + } + + client_log = logger.get_logger(f"{log.name}.client") + + def log_callback(client, userdata, level, buf): + client_log.log(LEVEL_MAP[level], buf) + + return log_callback + + def start(): """ This function runs on the module's dedicated process when it is started. Connections @@ -148,7 +177,7 @@ def start(): client.on_connect = on_connect client.on_disconnect = on_disconnect client.on_message = on_message # called for messages without a specfic subscriber - client.enable_logger(logger=logger.get_logger(f"{log.name}.client")) + client.on_log = client_logger() log.debug("Queuing connect event") client.connect_async(