Celery Task for Adding Arguments and Logging Results

  • Share this:

Code introduction


This function creates a Celery task that takes two arguments, adds them together, and logs the result to Celery's log.


Technology Stack : Celery, Python standard library (logging)

Code Type : Celery mission

Code Difficulty : Intermediate


                
                    
from celery import Celery
from celery.utils.log import get_task_logger

def random_task(arg1, arg2):
    # Initialize Celery app
    app = Celery('tasks', broker='pyamqp://guest@localhost//')
    
    # Get logger for the task
    logger = get_task_logger(__name__)
    
    # Log an info message
    logger.info('Task started with arguments: %s, %s', arg1, arg2)
    
    # Simulate some work
    result = arg1 + arg2
    
    # Log the result
    logger.info('Task finished with result: %s', result)
    
    return result