1. import json
  2. import logging
  3. # Configure logging
  4. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  5. CONFIG_FILE = "config.json" # Define the configuration file path
  6. def load_config(filepath=CONFIG_FILE):
  7. """Loads configuration from a JSON file with defensive checks."""
  8. try:
  9. with open(filepath, 'r') as f:
  10. config = json.load(f)
  11. return config
  12. except FileNotFoundError:
  13. logging.error(f"Configuration file not found: {filepath}")
  14. return {} # Return an empty dictionary if file not found.
  15. except json.JSONDecodeError as e:
  16. logging.error(f"Error decoding JSON in {filepath}: {e}")
  17. return {} # Return empty dict if JSON is invalid
  18. except Exception as e:
  19. logging.error(f"An unexpected error occurred while loading config: {e}")
  20. return {}
  21. def reload_config():
  22. """Reloads the configuration and performs defensive checks."""
  23. config = load_config()
  24. if not config:
  25. logging.warning("Failed to load configuration. Using default values.")
  26. return {} # Return empty dict if config is empty
  27. # Defensive checks: Validate required keys exist
  28. required_keys = ["strings"]
  29. for key in required_keys:
  30. if key not in config:
  31. logging.error(f"Missing required key: {key} in configuration.")
  32. return {} #Return empty dict if required key is missing
  33. if not isinstance(config["strings"], dict):
  34. logging.error("The 'strings' configuration must be a dictionary.")
  35. return {}
  36. #Example validation: Ensure each string has a length
  37. for string_key, string_value in config["strings"].items():
  38. if not isinstance(string_value, str):
  39. logging.error(f"String value for key '{string_key}' must be a string.")
  40. return {}
  41. if len(string_value) == 0:
  42. logging.warning(f"String value for key '{string_key}' is empty.")
  43. logging.info("Configuration reloaded and validated successfully.")
  44. return config

Add your comment