From 7148c849d6c9e1786f8af87172ea71501ff0546d Mon Sep 17 00:00:00 2001 From: Jan Bouwhuis Date: Tue, 7 May 2024 18:38:59 +0200 Subject: [PATCH] Only log loop client subscription log if log level is DEBUG (#117008) Co-authored-by: J. Nick Koston --- homeassistant/components/mqtt/client.py | 10 ++++++---- tests/components/mqtt/test_init.py | 13 +++++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/mqtt/client.py b/homeassistant/components/mqtt/client.py index e48a5ad3181..22833183b69 100644 --- a/homeassistant/components/mqtt/client.py +++ b/homeassistant/components/mqtt/client.py @@ -844,8 +844,9 @@ class MQTT: subscription_list = list(subscriptions.items()) result, mid = self._mqttc.subscribe(subscription_list) - for topic, qos in subscriptions.items(): - _LOGGER.debug("Subscribing to %s, mid: %s, qos: %s", topic, mid, qos) + if _LOGGER.isEnabledFor(logging.DEBUG): + for topic, qos in subscriptions.items(): + _LOGGER.debug("Subscribing to %s, mid: %s, qos: %s", topic, mid, qos) self._last_subscribe = time.monotonic() if result == 0: @@ -863,8 +864,9 @@ class MQTT: result, mid = self._mqttc.unsubscribe(topics) _raise_on_error(result) - for topic in topics: - _LOGGER.debug("Unsubscribing from %s, mid: %s", topic, mid) + if _LOGGER.isEnabledFor(logging.DEBUG): + for topic in topics: + _LOGGER.debug("Unsubscribing from %s, mid: %s", topic, mid) await self._async_wait_for_mid(mid) diff --git a/tests/components/mqtt/test_init.py b/tests/components/mqtt/test_init.py index 019f153c62a..a9f4a9f7454 100644 --- a/tests/components/mqtt/test_init.py +++ b/tests/components/mqtt/test_init.py @@ -1,9 +1,11 @@ """The tests for the MQTT component.""" import asyncio +from collections.abc import Generator from copy import deepcopy from datetime import datetime, timedelta import json +import logging import socket import ssl from typing import Any, TypedDict @@ -17,6 +19,7 @@ import voluptuous as vol from homeassistant.components import mqtt from homeassistant.components.mqtt import debug_info from homeassistant.components.mqtt.client import ( + _LOGGER as CLIENT_LOGGER, RECONNECT_INTERVAL_SECONDS, EnsureJobAfterCooldown, ) @@ -112,6 +115,15 @@ def record_calls(calls: list[ReceiveMessage]) -> MessageCallbackType: return record_calls +@pytest.fixture +def client_debug_log() -> Generator[None, None]: + """Set the mqtt client log level to DEBUG.""" + logger = logging.getLogger("mqtt_client_tests_debug") + logger.setLevel(logging.DEBUG) + with patch.object(CLIENT_LOGGER, "parent", logger): + yield + + def help_assert_message( msg: ReceiveMessage, topic: str | None = None, @@ -1000,6 +1012,7 @@ async def test_subscribe_topic_not_initialize( @patch("homeassistant.components.mqtt.client.UNSUBSCRIBE_COOLDOWN", 0.2) async def test_subscribe_and_resubscribe( hass: HomeAssistant, + client_debug_log: None, mqtt_mock_entry: MqttMockHAClientGenerator, mqtt_client_mock: MqttMockPahoClient, calls: list[ReceiveMessage],