From 55a3172e37855f388b9ba0dfc91641a6c9ad1376 Mon Sep 17 00:00:00 2001 From: Scott Date: Wed, 12 Jan 2022 09:06:29 -0800 Subject: [PATCH] Scale back warnings.warn and add stacklevels= where appropriate. --- arper.py | 2 +- base_presence.py | 6 +++--- camera_utils.py | 6 +++--- decorator_utils.py | 1 - executors.py | 4 ---- google_assistant.py | 2 +- lockfile.py | 4 ---- logging_utils.py | 2 -- persistent.py | 2 +- smart_home/lights.py | 3 --- smart_home/outlets.py | 3 --- smart_home/registry.py | 5 +---- string_utils.py | 6 +----- unittest_utils.py | 2 -- 14 files changed, 11 insertions(+), 37 deletions(-) diff --git a/arper.py b/arper.py index c0cc9f0..a4e8d3e 100644 --- a/arper.py +++ b/arper.py @@ -128,8 +128,8 @@ class Arper(persistent.Persistent): return cls(cached_state) else: msg = f'{cache_file} is invalid: only {len(cached_state)} entries. Deleting it.' - warnings.warn(msg) logger.warning(msg) + warnings.warn(msg, stacklevel=2) os.remove(cache_file) logger.debug('No usable saved state found') return None diff --git a/base_presence.py b/base_presence.py index b38b436..405b743 100755 --- a/base_presence.py +++ b/base_presence.py @@ -115,8 +115,8 @@ class PresenceDetection(object): except Exception as e: logger.exception(e) msg = "Can't see the cabin right now; presence detection impared." - logger.warning(msg) warnings.warn(msg) + logger.warning(msg, stacklevel=2) self.dark_locations.add(Location.CABIN) def update_from_cabin(self) -> None: @@ -136,7 +136,7 @@ class PresenceDetection(object): logger.exception(e) msg = "Can't see the house right now; presence detection impared." logger.warning(msg) - warnings.warn(msg) + warnings.warn(msg, stacklevel=2) self.dark_locations.add(Location.HOUSE) def read_persisted_macs_file( @@ -200,7 +200,7 @@ class PresenceDetection(object): if len(self.dark_locations) > 0: msg = f"Can't see {self.dark_locations} right now; answer confidence impacted" logger.warning(msg) - warnings.warn(msg) + warnings.warn(msg, stacklevel=2) logger.debug(f'Looking for {name}...') if name is Person.UNKNOWN: diff --git a/camera_utils.py b/camera_utils.py index e69eddb..83664fd 100644 --- a/camera_utils.py +++ b/camera_utils.py @@ -84,7 +84,7 @@ def fetch_camera_image_from_video_server( logger.exception(e) msg = f"Got a bad image or HTTP error from {url}; returning None." logger.warning(msg) - warnings.warn(msg) + warnings.warn(msg, stacklevel=2) return None @@ -135,8 +135,8 @@ def fetch_camera_image_from_rtsp_stream( except Exception as e: logger.exception(e) msg = "Failed to retrieve image via RTSP {stream}, returning None." - warnings.warn(msg) logger.warning(msg) + warnings.warn(msg, stacklevel=2) return None @@ -165,7 +165,7 @@ def _fetch_camera_image( ) msg = "Failed to retieve image from both video server and direct RTSP stream" logger.warning(msg) - warnings.warn(msg) + warnings.warn(msg, stacklevel=2) return RawJpgHsv(None, None, None) diff --git a/decorator_utils.py b/decorator_utils.py index 07ad881..752fb91 100644 --- a/decorator_utils.py +++ b/decorator_utils.py @@ -508,7 +508,6 @@ def thunkify(func): exc[1] = sys.exc_info() # (type, value, traceback) msg = f"Thunkify has thrown an exception (will be raised on thunk()):\n{traceback.format_exc()}" logger.warning(msg) - warnings.warn(msg) finally: wait_event.set() diff --git a/executors.py b/executors.py index 336f2c7..6ccd7b6 100644 --- a/executors.py +++ b/executors.py @@ -493,7 +493,6 @@ class WeightedRandomRemoteWorkerSelectionPolicy(RemoteWorkerSelectionPolicy): return worker msg = 'Unexpectedly could not find a worker, retrying...' logger.warning(msg) - warnings.warn(msg) return None @@ -530,7 +529,6 @@ class RoundRobinRemoteWorkerSelectionPolicy(RemoteWorkerSelectionPolicy): if x == self.index: msg = 'Unexpectedly could not find a worker, retrying...' logger.warning(msg) - warnings.warn(msg) return None @@ -777,7 +775,6 @@ class RemoteExecutor(BaseExecutor): msg += 'We\'re a backup and this may be caused by the original (or some ' msg += 'other backup) already finishing this work. Ignoring this.' logger.warning(msg) - warnings.warn(msg) return None # Kick off the work. Note that if this fails we let @@ -851,7 +848,6 @@ class RemoteExecutor(BaseExecutor): if p is not None: msg = f"{bundle}: Failed to wrap up \"done\" bundle, re-waiting on active ssh." logger.warning(msg) - warnings.warn(msg) return self.wait_for_process(p, bundle, depth + 1) else: self.status.record_release_worker( diff --git a/google_assistant.py b/google_assistant.py index 041648c..49c08d3 100644 --- a/google_assistant.py +++ b/google_assistant.py @@ -96,7 +96,7 @@ def ask_google(cmd: str, *, recognize_speech=True) -> GoogleResponse: logger.exception(e) msg = 'Unable to parse Google assistant\'s response.' logger.warning(msg) - warnings.warn(msg) + warnings.warn(msg, stacklevel=3) audio_transcription = None return GoogleResponse( success=success, diff --git a/lockfile.py b/lockfile.py index 7f10cc1..8a71ca7 100644 --- a/lockfile.py +++ b/lockfile.py @@ -90,7 +90,6 @@ class LockFile(object): pass msg = f'Could not acquire {self.lockfile}.' logger.warning(msg) - warnings.warn(msg) return False def acquire_with_retries( @@ -127,7 +126,6 @@ class LockFile(object): return self msg = f"Couldn't acquire {self.lockfile}; giving up." logger.warning(msg) - warnings.warn(msg) raise LockFileException(msg) def __exit__(self, type, value, traceback): @@ -178,7 +176,6 @@ class LockFile(object): except OSError: msg = f'Lockfile {self.lockfile}\'s pid ({contents.pid}) is stale; force acquiring' logger.warning(msg) - warnings.warn(msg) self.release() # Has the lock expiration expired? @@ -187,7 +184,6 @@ class LockFile(object): if now > contents.expiration_datetime: msg = f'Lockfile {self.lockfile} expiration time has passed; force acquiring' logger.warning(msg) - warnings.warn(msg) self.release() except Exception: pass diff --git a/logging_utils.py b/logging_utils.py index 20a57f7..f7fac03 100644 --- a/logging_utils.py +++ b/logging_utils.py @@ -13,7 +13,6 @@ import os import random import sys from typing import Callable, Iterable, Mapping, Optional -import warnings from overrides import overrides import pytz @@ -526,7 +525,6 @@ def initialize_logging(logger=None) -> logging.Logger: if config.config['logging_clear_preexisting_handlers'] and preexisting_handlers_count > 0: msg = 'Logging cleared {preexisting_handlers_count} global handlers (--logging_clear_preexisting_handlers)' logger.warning(msg) - warnings.warn(msg) logger.debug(f'Logging format specification is "{fmt}"') if config.config['logging_debug_threads']: logger.debug('...Logging format spec captures tid/pid (--logging_debug_threads)') diff --git a/persistent.py b/persistent.py index 2751572..83e6900 100644 --- a/persistent.py +++ b/persistent.py @@ -146,7 +146,7 @@ class persistent_autoloaded_singleton(object): if not self.instance: msg = 'Loading from cache failed.' logger.warning(msg) - warnings.warn(msg) + warnings.warn(msg, stacklevel=2) logger.debug(f'Attempting to instantiate {cls.__name__} directly.') self.instance = cls(*args, **kwargs) else: diff --git a/smart_home/lights.py b/smart_home/lights.py index 44b3634..237d4e0 100644 --- a/smart_home/lights.py +++ b/smart_home/lights.py @@ -11,7 +11,6 @@ import re import subprocess import sys from typing import Any, Dict, List, Optional, Tuple -import warnings from overrides import overrides import tinytuya as tt @@ -49,7 +48,6 @@ def tplink_light_command(command: str) -> bool: if signal != 0: msg = f'{command} died with signal {signal}' logger.warning(msg) - warnings.warn(msg) logging_utils.hlog(msg) return False else: @@ -57,7 +55,6 @@ def tplink_light_command(command: str) -> bool: if exit_value != 0: msg = f'{command} failed, exited {exit_value}' logger.warning(msg) - warnings.warn(msg) logging_utils.hlog(msg) return False logger.debug(f'{command} succeeded.') diff --git a/smart_home/outlets.py b/smart_home/outlets.py index 6cc8d57..c079cfd 100644 --- a/smart_home/outlets.py +++ b/smart_home/outlets.py @@ -13,7 +13,6 @@ import re import subprocess import sys from typing import Any, Dict, List, Optional -import warnings from meross_iot.http_api import MerossHttpClient from meross_iot.manager import MerossManager @@ -51,7 +50,6 @@ def tplink_outlet_command(command: str) -> bool: if signal != 0: msg = f'{command} died with signal {signal}' logger.warning(msg) - warnings.warn(msg) logging_utils.hlog(msg) return False else: @@ -59,7 +57,6 @@ def tplink_outlet_command(command: str) -> bool: if exit_value != 0: msg = f'{command} failed, exited {exit_value}' logger.warning(msg) - warnings.warn(msg) logging_utils.hlog(msg) return False logger.debug(f'{command} succeeded.') diff --git a/smart_home/registry.py b/smart_home/registry.py index 20fb3f4..75fe052 100644 --- a/smart_home/registry.py +++ b/smart_home/registry.py @@ -3,7 +3,6 @@ import logging import re from typing import List, Optional, Set -import warnings import argparse_utils import config @@ -64,9 +63,8 @@ class SmartHomeRegistry(object): try: (mac, name, keywords) = line.split(",") except ValueError: - msg = f'SH-CONFIG> {line} is malformed?!' + msg = f'SH-CONFIG> "{line}" is malformed?! Skipping it.' logger.warning(msg) - warnings.warn(msg) continue mac = mac.strip() name = name.strip() @@ -190,7 +188,6 @@ class SmartHomeRegistry(object): return device.Device(name, mac, kws) msg = f'{mac} is not a known smart home device, returning None' logger.warning(msg) - warnings.warn(msg) return None def query(self, query: str) -> List[device.Device]: diff --git a/string_utils.py b/string_utils.py index b93dc93..6eda278 100644 --- a/string_utils.py +++ b/string_utils.py @@ -1100,7 +1100,6 @@ def to_date(in_str: str) -> Optional[datetime.date]: except dp.ParseException: msg = f'Unable to parse date {in_str}.' logger.warning(msg) - warnings.warn(msg) return None @@ -1116,7 +1115,6 @@ def valid_date(in_str: str) -> bool: except dp.ParseException: msg = f'Unable to parse date {in_str}.' logger.warning(msg) - warnings.warn(msg) return False @@ -1133,7 +1131,6 @@ def to_datetime(in_str: str) -> Optional[datetime.datetime]: except ValueError: msg = f'Unable to parse datetime {in_str}.' logger.warning(msg) - warnings.warn(msg) return None @@ -1146,7 +1143,6 @@ def valid_datetime(in_str: str) -> bool: return True msg = f'Unable to parse datetime {in_str}.' logger.warning(msg) - warnings.warn(msg) return False @@ -1477,7 +1473,7 @@ def chunk(txt: str, chunk_size): if len(txt) % chunk_size != 0: msg = f'String to chunk\'s length ({len(txt)} is not an even multiple of chunk_size ({chunk_size})' logger.warning(msg) - warnings.warn(msg) + warnings.warn(msg, stacklevel=2) for x in range(0, len(txt), chunk_size): yield txt[x:x+chunk_size] diff --git a/unittest_utils.py b/unittest_utils.py index 270e20d..8c9a120 100644 --- a/unittest_utils.py +++ b/unittest_utils.py @@ -18,7 +18,6 @@ import time import tempfile from typing import Callable import unittest -import warnings import bootstrap import config @@ -81,7 +80,6 @@ def check_method_for_perf_regressions(func: Callable) -> Callable: logger.exception(e) msg = f'Unable to load perfdb from {_db}' logger.warning(msg) - warnings.warn(msg) perfdb = {} # This is a unique identifier for a test: filepath!function -- 2.45.2