import traceback
from .models import ErrorLog

def log_error(task_source, error):
    """
    Log an error to the database
    
    Args:
        task_source (str): The source of the error (method, controller, view name)
        error (Exception or str): The error object or error message
    """
    try:
        # If error is an exception, get the full traceback
        if isinstance(error, Exception):
            error_message = f"{str(error)}\n{traceback.format_exc()}"
        else:
            error_message = str(error)
            
        # Create the error log entry
        ErrorLog.objects.create(
            task_source=task_source,
            error=error_message
        )
    except Exception as e:
        # If logging fails, print to console as fallback
        print(f"Failed to log error: {str(e)}")
        print(f"Original error from {task_source}: {str(error)}") 