CoolFace
Apppublic

cesmith012/technical-assistant

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
log_utils.py107 linesDownload Raw Back to root
1 2import os3import logging4from logging.handlers import RotatingFileHandler5from pathlib import Path6from datetime import datetime7 8def setup_logging(app_name: str = "kta") -> logging.Logger:9    """10    Set up logging configuration for the application.11    12    Args:13        app_name (str): Name of the application for the logger14        15    Returns:16        logging.Logger: Configured logger instance17    """18    try:19        # Create log directory based on environment20        is_huggingface = bool(os.getenv('SPACE_ID'))21        22        if is_huggingface:23            log_dir = Path("/tmp")24        else:25            log_dir = Path("G:/APPS/Technical Assistant")26            27        log_dir.mkdir(parents=True, exist_ok=True)28        29        # Create log file path with date30        current_date = datetime.now().strftime("%Y%m%d")31        log_file = log_dir / f"kta_logs_{current_date}.txt"32        33        # Create a logger34        logger = logging.getLogger(app_name)35        logger.setLevel(logging.DEBUG)36        37        # Clear existing handlers (to avoid duplicates)38        if logger.handlers:39            logger.handlers.clear()40        41        # Create handlers42        # File handler with rotation (10MB max size, keep 30 backup files)43        file_handler = RotatingFileHandler(44            filename=log_file,45            maxBytes=10*1024*1024,  # 10MB46            backupCount=30,47            encoding='utf-8'48        )49        file_handler.setLevel(logging.DEBUG)50        51        # Console handler52        console_handler = logging.StreamHandler()53        console_handler.setLevel(logging.INFO)54        55        # Create formatters and add it to handlers56        file_format = logging.Formatter(57            '%(asctime)s [%(levelname)s] %(name)s - %(message)s',58            datefmt='%Y-%m-%d %H:%M:%S'59        )60        console_format = logging.Formatter('%(levelname)s: %(message)s')61        62        file_handler.setFormatter(file_format)63        console_handler.setFormatter(console_format)64        65        # Add handlers to the logger66        logger.addHandler(file_handler)67        logger.addHandler(console_handler)68        69        logger.info(f"Logging initialized. Log file: {log_file}")70        return logger71        72    except Exception as e:73        # If we can't set up logging to file, set up basic console logging74        logging.basicConfig(level=logging.INFO)75        logger = logging.getLogger(app_name)76        logger.error(f"Failed to initialize file logging: {str(e)}")77        return logger78 79def get_logger(name: str = "kta") -> logging.Logger:80    """81    Get a logger instance. If it doesn't exist, create a new one.82    83    Args:84        name (str): Name for the logger85        86    Returns:87        logging.Logger: Logger instance88    """89    logger = logging.getLogger(name)90    91    # If logger has no handlers, set it up92    if not logger.handlers:93        logger = setup_logging(name)94    95    return logger96 97# Example usage98if __name__ == "__main__":99    # Test the logging configuration100    logger = get_logger("kta_test")101    logger.debug("This is a debug message")102    logger.info("This is an info message")103    logger.warning("This is a warning message")104    logger.error("This is an error message")105    logger.critical("This is a critical message") 106 107