import configparser
import logging
import os
# Configure logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
def read_config(config_file):
"""Reads configuration from a file. Handles file not found.
"""
config = configparser.ConfigParser()
try:
config.read(config_file)
logging.debug(f"Successfully read configuration from: {config_file}")
return config
except FileNotFoundError:
logging.error(f"Configuration file not found: {config_file}")
return None
except configparser.Error as e:
logging.error(f"Error parsing configuration file {config_file}: {e}")
return None
def get_config_value(config, section, key):
"""Retrieves a value from the configuration. Handles missing sections/keys.
"""
if config and config.has_section(section):
value = config.get(section, key)
logging.debug(f"Retrieved value '{value}' from section '{section}', key '{key}'")
return value
else:
logging.warning(f"Section '{section}' or key '{key}' not found in configuration.")
return None
if __name__ == '__main__':
# Example usage with development config file
config_file = "config_dev.ini"
# Create a dummy config file if it doesn't exist
if not os.path.exists(config_file):
with open(config_file, "w") as f:
f.write("""
[database]
host = localhost
port = 5432
user = devuser
password = devpassword
[api]
base_url = http://localhost:8000/api
debug = True
""")
logging.info(f"Created dummy configuration file: {config_file}")
config = read_config(config_file)
if config:
db_host = get_config_value(config, "database", "host")
db_port = get_config_value(config, "database", "port")
api_url = get_config_value(config, "api", "base_url")
debug_mode = get_config_value(config, "api", "debug")
logging.debug(f"Database Host: {db_host}")
logging.debug(f"Database Port: {db_port}")
logging.debug(f"API URL: {api_url}")
logging.debug(f"Debug Mode: {debug_mode}")
Add your comment