Random String Generation and Celery Logging

  • Share this:

Code introduction


This function uses the Celery library to generate a random string and log it using Celery's logger. It first initializes a Celery application, then gets a logger using `get_task_logger`, generates a random string of a specified length, and logs it as a log message.


Technology Stack : Celery, Python standard library

Code Type : Celery task

Code Difficulty : Intermediate


                
                    
def random_task_message(message_length=10):
    import random
    from celery.utils.log import get_task_logger
    from celery import Celery

    # Initialize Celery with a fake broker and backend
    app = Celery('tasks', broker='pyamqp://', backend='rpc://')

    # Get a logger
    logger = get_task_logger(__name__)

    # Generate a random message of a given length
    message = ''.join(random.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=message_length))

    # Log the message using Celery's logger
    logger.info(f'Generated message: {message}')

    return message