Mayil-AI-Sandbox / loguru-Jan2023

MIT License
0 stars 0 forks source link

How to display taskName of async task in loguru? (hashtag1161) #152

Open vikramsubramanian opened 2 weeks ago

vikramsubramanian commented 2 weeks ago

as of Python 3.12, [logging module supports taskName](

taskName
%(taskName)s
[asyncio.Task]( name (if available).

If Anyone know how to display taskName in loguru format? Thanks a lot. )

mayil-ai[bot] commented 2 weeks ago

Some past issues to consider:

Here are some code snippets that may help you get started:

To display the taskName of an asynchronous task in Loguru logs, follow these steps:

  1. Import Necessary Modules: Ensure you have the necessary imports, including asyncio to access the current task and loguru for logging.

  2. Define a Custom Formatter: Create a custom formatter function that extracts the task name from the current asyncio task and includes it in the log record.

  3. Update Loguru Configuration: Configure Loguru to use the custom formatter.

Here’s a complete example:

from loguru import logger
import asyncio
import sys

def custom_formatter(record):
    # Attempt to get the current asyncio task
    task = asyncio.current_task()
    task_name = task.get_name() if task else "NoTask"

    # Add task name to the record's extra dictionary
    record["extra"]["task_name"] = task_name

    # Define the log format
    format_string = (
        "<green>{time}</green> | <level>{level: <8}</level> | "
        "<cyan>{name}:{function}:{line}</cyan> | "
        "<yellow>{extra[task_name]}</yellow> - <level>{message}</level>\n{exception}"
    )

    return format_string

# Configure loguru to use the custom formatter
logger.configure(handlers=[{"sink": sys.stdout, "format": custom_formatter}])

# Example async function to demonstrate logging
async def example_task():
    logger.info("This is a log message from an async task.")

# Run the example task
asyncio.run(example_task())

Relevant References:

Potential Implications:

  1. Performance Overhead: Adding extra information to log records can introduce a slight performance overhead, especially if logging is done frequently.
  2. Compatibility: Ensure that the environment where this code runs supports Python 3.12 or later for the taskName feature in the logging module.
  3. Error Handling: The custom formatter should handle cases where there is no current task gracefully, as shown in the example.

💡 To rerun Mayil, comment mayil-ai rerun. Mayil will incorporate any new context added to the ticket. Include details in your rerun comment to guide Mayil!