Celery-Integrated Random Number Generator with Logging

  • Share this:

Code introduction


This function uses Celery's logging functionality to log the operation of generating a random number. It accepts two parameters a and b, and then generates a random integer within this range using the randint function from the random library. If an exception occurs during the generation process, it will log this error.


Technology Stack : Celery, random, logging

Code Type : Function

Code Difficulty : Intermediate


                
                    
def generate_random_number(a, b):
    from celery.utils.log import get_task_logger
    import random
    logger = get_task_logger(__name__)
    try:
        num = random.randint(a, b)
        logger.info(f"Generated random number: {num}")
        return num
    except Exception as e:
        logger.error(f"Error generating random number: {e}")