import logging
import sys
import os            
from fortress.config import get_config

def setup_logging():
    config = get_config()['logging']
    log_level = config.get('level', 'INFO').upper()
    log_format = config.get('format', '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    log_file = config.get('log_file')

    logger = logging.getLogger("fortress")                                  
    logger.setLevel(log_level)
                                                                           
    if logger.hasHandlers():
        logger.handlers.clear()

    formatter = logging.Formatter(log_format)

                     
    ch = logging.StreamHandler(sys.stdout)
    ch.setFormatter(formatter)
    logger.addHandler(ch)

                             
    if log_file:
                                                      
        log_dir = os.path.dirname(log_file)
        if log_dir and not os.path.exists(log_dir):
            os.makedirs(log_dir, exist_ok=True)
            
        fh = logging.FileHandler(log_file)
        fh.setFormatter(formatter)
        logger.addHandler(fh)
    
    return logger

                                                
logger = setup_logging()

                          
                                                
                                         
                                           
