Skip to content

Commit

Permalink
Merge pull request #244 from Snuffy2/Turn-down-debug-logging
Browse files Browse the repository at this point in the history
Logging refinements
  • Loading branch information
alexdelprete authored Oct 9, 2024
2 parents 14ab6ed + 6c34a56 commit 970a0dc
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 41 deletions.
34 changes: 7 additions & 27 deletions custom_components/opnsense/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,22 +77,6 @@ async def _get_states(self, categories: list) -> Mapping[str, Any]:
)
return state

async def _get_dhcp_stats(self, leases: list) -> Mapping[str, Any]:
lease_stats: Mapping[str, Any] = {"total": 0, "online": 0, "offline": 0}
if not isinstance(leases, list):
return lease_stats
for lease in leases:
if not isinstance(lease, Mapping) or lease.get("act", "") == "expired":
continue

lease_stats["total"] += 1
if "online" in lease:
if lease["online"] == "online":
lease_stats["online"] += 1
if lease["online"] == "offline":
lease_stats["offline"] += 1
return lease_stats

@_log_timing
async def _async_update_data(self) -> Mapping[str, Any]:
"""Fetch the latest state from OPNsense."""
Expand Down Expand Up @@ -164,23 +148,19 @@ async def _async_update_data(self) -> Mapping[str, Any]:
]

self._state.update(await self._get_states(categories))
if self._state.get("device_unique_id") is None:
_LOGGER.warning(
"Coordinator failed to confirm OPNsense Router Unique ID. Will retry"
)
return {}
if self._state.get("device_unique_id") != self._device_unique_id:
_LOGGER.error(
"Coordinator error. OPNsense Router Device ID differs from the one saved in hass-opnsense."
f"Coordinator error. OPNsense Router Device ID ({self._state.get('device_unique_id')}) differs from the one saved in hass-opnsense ({self._device_unique_id})"
)
# Create repair task here
return {}
if self._state.get("device_unique_id") is None:
_LOGGER.warning("Coordinator failed to confirm OPNsense Router Unique ID")
return {}

_LOGGER.debug(
f"[async_update_data] dhcp_leases: {self._state.get('dhcp_leases', {})}"
)
# self._state["dhcp_stats"] = {}
# self._state["dhcp_stats"]["leases"] = await self._get_dhcp_stats(
# self._state.get("dhcp_leases", [])
# )
# _LOGGER.debug(f"[async_update_data] dhcp_leases: {self._state.get('dhcp_leases', {})}")

# calcule pps and kbps
update_time = dict_get(self._state, "update_time")
Expand Down
16 changes: 11 additions & 5 deletions custom_components/opnsense/pyopnsense/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import socket
import ssl
import time
import traceback
import xmlrpc.client
from abc import ABC
from collections.abc import Mapping
Expand Down Expand Up @@ -123,7 +124,7 @@ async def inner(self, *args, **kwargs):
r"(\w+):(\w+)@", "<redacted>:<redacted>@", str(e)
)
_LOGGER.error(
f"Error in {func.__name__.strip('_')}. {e.__class__.__qualname__}: {redacted_message}"
f"Error in {func.__name__.strip('_')}. {e.__class__.__qualname__}: {redacted_message}\n{''.join(traceback.format_tb(e.__traceback__))}"
)
if self._initial:
raise e
Expand Down Expand Up @@ -188,12 +189,17 @@ async def _exec_php(self, script) -> Mapping[str, Any]:
return response_json
except TypeError as e:
_LOGGER.error(
f"Invalid data returned from exec_php for {inspect.currentframe().f_back.f_code.co_qualname.strip('_')}. {e.__class__.__qualname__}: {e}. Ensure the OPNsense user connected to HA either has full Admin access or specifically has the 'XMLRPC Library' privilege."
f"Invalid data returned from exec_php for {inspect.currentframe().f_back.f_code.co_qualname.strip('_')}. {e.__class__.__qualname__}: {e}. Ensure the OPNsense user connected to HA either has full Admin access or specifically has the 'XMLRPC Library' privilege"
)
return {}
except xmlrpc.client.Fault as e:
_LOGGER.error(
f"Error running exec_php script for {inspect.currentframe().f_back.f_code.co_qualname.strip('_')}. {e.__class__.__qualname__}: {e}. Ensure the 'os-homeassistant-maxit' plugin has been installed on OPNsense ."
f"Error running exec_php script for {inspect.currentframe().f_back.f_code.co_qualname.strip('_')}. {e.__class__.__qualname__}: {e}. Ensure the 'os-homeassistant-maxit' plugin has been installed on OPNsense"
)
return {}
except socket.gaierror as e:
_LOGGER.warning(
f"Connection Error running exec_php script for {inspect.currentframe().f_back.f_code.co_qualname.strip('_')}. {e.__class__.__qualname__}: {e}. Will retry"
)
return {}

Expand Down Expand Up @@ -279,7 +285,7 @@ async def _get(self, path: str) -> Mapping[str, Any] | list:
return response_json
if response.status == 403:
_LOGGER.error(
f"Permission Error in {inspect.currentframe().f_back.f_code.co_qualname.strip('_')}. Path: {url}. Ensure the OPNsense user connected to HA has full Admin access."
f"Permission Error in {inspect.currentframe().f_back.f_code.co_qualname.strip('_')}. Path: {url}. Ensure the OPNsense user connected to HA has full Admin access"
)
else:
_LOGGER.error(
Expand Down Expand Up @@ -313,7 +319,7 @@ async def _post(self, path: str, payload=None) -> Mapping[str, Any] | list:
return response_json
elif response.status == 403:
_LOGGER.error(
f"Permission Error in {inspect.currentframe().f_back.f_code.co_qualname.strip('_')}. Path: {url}. Ensure the OPNsense user connected to HA has full Admin access."
f"Permission Error in {inspect.currentframe().f_back.f_code.co_qualname.strip('_')}. Path: {url}. Ensure the OPNsense user connected to HA has full Admin access"
)
else:
_LOGGER.error(
Expand Down
12 changes: 3 additions & 9 deletions custom_components/opnsense/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -792,18 +792,12 @@ def _handle_coordinator_update(self) -> None:
if not isinstance(state, Mapping):
return
if_name: str = self.entity_description.key.split(".")[1].strip()
_LOGGER.debug(
f"[OPNsenseDHCPLeasesSensor handle_coordinator_update] if_name: {if_name}"
)
# _LOGGER.debug(f"[OPNsenseDHCPLeasesSensor handle_coordinator_update] if_name: {if_name}")
if if_name.lower() == "all":
leases = state.get("dhcp_leases", {}).get("leases", {})
lease_interfaces = state.get("dhcp_leases", {}).get("lease_interfaces", {})
_LOGGER.debug(
f"[OPNsenseDHCPLeasesSensor handle_coordinator_update] lease_interfaces: {lease_interfaces}"
)
_LOGGER.debug(
f"[OPNsenseDHCPLeasesSensor handle_coordinator_update] leases: {leases}"
)
# _LOGGER.debug(f"[OPNsenseDHCPLeasesSensor handle_coordinator_update] lease_interfaces: {lease_interfaces}")
# _LOGGER.debug(f"[OPNsenseDHCPLeasesSensor handle_coordinator_update] leases: {leases}")
if not isinstance(leases, Mapping) or not isinstance(
lease_interfaces, Mapping
):
Expand Down

0 comments on commit 970a0dc

Please sign in to comment.