import logging
from logging.handlers import RotatingFileHandler
from datetime import datetime

# Custom formatter class
class CustomFormatter(logging.Formatter):
    def formatTime(self, record, datefmt=None):
        record_time = datetime.fromtimestamp(record.created)
        return record_time.strftime('%d-%m-%Y %H:%M:%S') + f".{record_time.microsecond // 1000:03}"

# Enhanced logging configuration with rotating file handler
def setup_logging(app):
    logHandler = RotatingFileHandler(app.config['LOG_FILE'], maxBytes=app.config['LOG_MAX_BYTES'], backupCount=app.config['LOG_BACKUP_COUNT'])
    logHandler.setLevel(logging.INFO)
    formatter = CustomFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    logHandler.setFormatter(formatter)
    app.logger.addHandler(logHandler)

    # Add a basic console handler (optional)
    consoleHandler = logging.StreamHandler()
    consoleHandler.setLevel(logging.INFO)
    consoleHandler.setFormatter(formatter)
    app.logger.addHandler(consoleHandler)

    # Set the application's logger to use the configured handlers
    app.logger.setLevel(logging.INFO)
