import json
import logging
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
CONFIG_FILE = "config.json" # Define the configuration file path
def load_config(filepath=CONFIG_FILE):
"""Loads configuration from a JSON file with defensive checks."""
try:
with open(filepath, 'r') as f:
config = json.load(f)
return config
except FileNotFoundError:
logging.error(f"Configuration file not found: {filepath}")
return {} # Return an empty dictionary if file not found.
except json.JSONDecodeError as e:
logging.error(f"Error decoding JSON in {filepath}: {e}")
return {} # Return empty dict if JSON is invalid
except Exception as e:
logging.error(f"An unexpected error occurred while loading config: {e}")
return {}
def reload_config():
"""Reloads the configuration and performs defensive checks."""
config = load_config()
if not config:
logging.warning("Failed to load configuration. Using default values.")
return {} # Return empty dict if config is empty
# Defensive checks: Validate required keys exist
required_keys = ["strings"]
for key in required_keys:
if key not in config:
logging.error(f"Missing required key: {key} in configuration.")
return {} #Return empty dict if required key is missing
if not isinstance(config["strings"], dict):
logging.error("The 'strings' configuration must be a dictionary.")
return {}
#Example validation: Ensure each string has a length
for string_key, string_value in config["strings"].items():
if not isinstance(string_value, str):
logging.error(f"String value for key '{string_key}' must be a string.")
return {}
if len(string_value) == 0:
logging.warning(f"String value for key '{string_key}' is empty.")
logging.info("Configuration reloaded and validated successfully.")
return config
Add your comment