Celery-based Task Logger with Retry Mechanism

  • Share this:

Code introduction


This function uses the Celery library's logging and retry features to define a function named random_task_name that accepts a task_id parameter and performs a task. The task logs its running status and retries if an exception occurs.


Technology Stack : Celery, logging, retry

Code Type : Celery task function

Code Difficulty : Intermediate


                
                    
def random_task_name(task_id):
    from celery.utils.log import get_task_logger
    from celery.utils.retry import retry

    logger = get_task_logger(__name__)
    
    @retry(5, exc=Exception)
    def task():
        logger.info(f"Task {task_id} is running.")
        return f"Task {task_id} completed."

    return task()