Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adjust remote ESPHome log subscription level on logging change #139308

Merged
merged 7 commits into from
Feb 26, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion homeassistant/components/esphome/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
Platform,
)
from homeassistant.core import (
CALLBACK_TYPE,
Event,
EventStateChangedData,
HomeAssistant,
Expand Down Expand Up @@ -95,6 +96,14 @@
LogLevel.LOG_LEVEL_VERBOSE: logging.DEBUG,
LogLevel.LOG_LEVEL_VERY_VERBOSE: logging.DEBUG,
}
LOGGER_TO_LOG_LEVEL = {
logging.NOTSET: LogLevel.LOG_LEVEL_VERY_VERBOSE,
logging.DEBUG: LogLevel.LOG_LEVEL_VERY_VERBOSE,
logging.INFO: LogLevel.LOG_LEVEL_CONFIG,
logging.WARNING: LogLevel.LOG_LEVEL_WARN,
logging.ERROR: LogLevel.LOG_LEVEL_ERROR,
logging.CRITICAL: LogLevel.LOG_LEVEL_ERROR,
}
# 7-bit and 8-bit C1 ANSI sequences
# https://stackoverflow.com/questions/14693701/how-can-i-remove-the-ansi-escape-sequences-from-a-string-in-python
ANSI_ESCAPE_78BIT = re.compile(
Expand Down Expand Up @@ -161,6 +170,8 @@
"""Class to manage an ESPHome connection."""

__slots__ = (
"_cancel_subscribe_logs",
"_log_level",
"cli",
"device_id",
"domain_data",
Expand Down Expand Up @@ -194,6 +205,8 @@
self.reconnect_logic: ReconnectLogic | None = None
self.zeroconf_instance = zeroconf_instance
self.entry_data = entry.runtime_data
self._cancel_subscribe_logs: CALLBACK_TYPE | None = None
self._log_level = LogLevel.LOG_LEVEL_NONE

async def on_stop(self, event: Event) -> None:
"""Cleanup the socket client on HA close."""
Expand Down Expand Up @@ -378,6 +391,24 @@
ANSI_ESCAPE_78BIT.sub(b"", log).decode("utf-8", "backslashreplace"),
)

@callback
def _async_get_equivalent_log_level(self) -> LogLevel:
"""Get the equivalent ESPHome log level for the current logger."""
return LOGGER_TO_LOG_LEVEL.get(
_LOGGER.getEffectiveLevel(), LogLevel.LOG_LEVEL_VERY_VERBOSE
)

@callback
def _async_subscribe_logs(self, log_level: LogLevel) -> None:
"""Subscribe to logs."""
if self._cancel_subscribe_logs is not None:
self._cancel_subscribe_logs()
self._cancel_subscribe_logs = None

Check warning on line 406 in homeassistant/components/esphome/manager.py

View check run for this annotation

Codecov / codecov/patch

homeassistant/components/esphome/manager.py#L405-L406

Added lines #L405 - L406 were not covered by tests
self._log_level = log_level
self._cancel_subscribe_logs = self.cli.subscribe_logs(
self._async_on_log, self._log_level
)

async def _on_connnect(self) -> None:
"""Subscribe to states and list entities on successful API login."""
entry = self.entry
Expand All @@ -390,7 +421,7 @@
stored_device_name = entry.data.get(CONF_DEVICE_NAME)
unique_id_is_mac_address = unique_id and ":" in unique_id
if entry.options.get(CONF_SUBSCRIBE_LOGS):
cli.subscribe_logs(self._async_on_log, LogLevel.LOG_LEVEL_VERY_VERBOSE)
self._async_subscribe_logs(self._async_get_equivalent_log_level())
results = await asyncio.gather(
create_eager_task(cli.device_info()),
create_eager_task(cli.list_entities_services()),
Expand Down Expand Up @@ -542,6 +573,10 @@
def _async_handle_logging_changed(self, _event: Event) -> None:
"""Handle when the logging level changes."""
self.cli.set_debug(_LOGGER.isEnabledFor(logging.DEBUG))
if self.entry.options.get(CONF_SUBSCRIBE_LOGS) and self._log_level != (
new_log_level := self._async_get_equivalent_log_level()
):
self._async_subscribe_logs(new_log_level)

async def async_start(self) -> None:
"""Start the esphome connection manager."""
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/esphome/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"loggers": ["aioesphomeapi", "noiseprotocol", "bleak_esphome"],
"mqtt": ["esphome/discover/#"],
"requirements": [
"aioesphomeapi==29.1.1",
"aioesphomeapi==29.2.0",
"esphome-dashboard-api==1.2.3",
"bleak-esphome==2.7.1"
],
Expand Down
2 changes: 1 addition & 1 deletion requirements_all.txt

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion requirements_test_all.txt

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions tests/components/esphome/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,7 @@ def __init__(
)
self.on_log_message: Callable[[SubscribeLogsResponse], None]
self.device_info = device_info
self.current_log_level = LogLevel.LOG_LEVEL_NONE

def set_state_callback(self, state_callback: Callable[[EntityState], None]) -> None:
"""Set the state callback."""
Expand Down Expand Up @@ -435,6 +436,7 @@ def _subscribe_logs(
) -> None:
"""Subscribe to log messages."""
mock_device.set_on_log_message(on_log_message)
mock_device.current_log_level = log_level

def _subscribe_voice_assistant(
*,
Expand Down
18 changes: 18 additions & 0 deletions tests/components/esphome/test_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ async def test_esphome_device_subscribe_logs(
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test configuring a device to subscribe to logs."""
assert await async_setup_component(hass, "logger", {"logger": {}})
entry = MockConfigEntry(
domain=DOMAIN,
data={
Expand All @@ -76,6 +77,15 @@ async def test_esphome_device_subscribe_logs(
states=[],
)
await hass.async_block_till_done()

await hass.services.async_call(
"logger",
"set_level",
{"homeassistant.components.esphome": "DEBUG"},
blocking=True,
)
assert device.current_log_level == LogLevel.LOG_LEVEL_VERY_VERBOSE

caplog.set_level(logging.DEBUG)
device.mock_on_log_message(
Mock(level=LogLevel.LOG_LEVEL_INFO, message=b"test_log_message")
Expand Down Expand Up @@ -103,6 +113,14 @@ async def test_esphome_device_subscribe_logs(
await hass.async_block_till_done()
assert "test_debug_log_message" in caplog.text

await hass.services.async_call(
"logger",
"set_level",
{"homeassistant.components.esphome": "WARNING"},
blocking=True,
)
assert device.current_log_level == LogLevel.LOG_LEVEL_WARN


async def test_esphome_device_service_calls_not_allowed(
hass: HomeAssistant,
Expand Down