diff --git a/datareservoirio/_logging.py b/datareservoirio/_logging.py index b9d3b481..ac5fb023 100644 --- a/datareservoirio/_logging.py +++ b/datareservoirio/_logging.py @@ -1,6 +1,7 @@ import logging import os -from functools import cache, wraps +import threading +from functools import lru_cache, wraps from azure.monitor.opentelemetry import configure_azure_monitor @@ -9,8 +10,24 @@ from ._constants import ENV_VAR_ENABLE_APP_INSIGHTS, ENV_VAR_ENGINE_ROOM_APP_ID from .globalsettings import environment +_configure_lock = threading.Lock() +_configured_loggers = {} -@cache + +def _ensure_azure_monitor_configured(connection_string, logger_name): + cache_key = (connection_string, logger_name) + + if cache_key not in _configured_loggers: + with _configure_lock: + # Double-check locking + if cache_key not in _configured_loggers: + configure_azure_monitor( + connection_string=connection_string, logger_name=logger_name + ) + _configured_loggers[cache_key] = True + + +@lru_cache(maxsize=1) def get_exceptions_logger() -> logging.Logger: exceptions_logger = logging.getLogger(__name__ + "_exception_logger") exceptions_logger.setLevel(logging.DEBUG) @@ -18,7 +35,7 @@ def get_exceptions_logger() -> logging.Logger: if os.getenv(ENV_VAR_ENABLE_APP_INSIGHTS) is not None: enable_app_insights = os.environ[ENV_VAR_ENABLE_APP_INSIGHTS].lower() if enable_app_insights == "true" or enable_app_insights == "1": - configure_azure_monitor( + _ensure_azure_monitor_configured( connection_string=environment._application_insight_connectionstring, logger_name=__name__ + "_exceptions_logger", ) diff --git a/datareservoirio/client.py b/datareservoirio/client.py index bbb6337a..35a53b42 100644 --- a/datareservoirio/client.py +++ b/datareservoirio/client.py @@ -5,7 +5,7 @@ from collections import defaultdict from concurrent.futures import ThreadPoolExecutor from datetime import datetime -from functools import cache, wraps +from functools import lru_cache, wraps from operator import itemgetter from urllib.parse import urlencode from uuid import uuid4 @@ -25,7 +25,7 @@ from datareservoirio._constants import ENV_VAR_ENABLE_APP_INSIGHTS -from ._logging import log_decorator +from ._logging import _ensure_azure_monitor_configured, log_decorator from ._utils import function_translation, period_translation from .globalsettings import environment from .storage import Storage @@ -33,14 +33,14 @@ log = logging.getLogger(__name__) -@cache +@lru_cache(maxsize=1) def metric() -> logging.Logger: logger = logging.getLogger(__name__ + "_metric_appinsight") if os.getenv(ENV_VAR_ENABLE_APP_INSIGHTS) is not None: enable_app_insights = os.environ[ENV_VAR_ENABLE_APP_INSIGHTS].lower() if enable_app_insights == "true" or enable_app_insights == "1": logger.setLevel(logging.DEBUG) - configure_azure_monitor( + _ensure_azure_monitor_configured( connection_string=environment._application_insight_connectionstring, logger_name=__name__ + "_metric_appinsight", )