Open vikramsubramanian opened 2 weeks ago
To display the taskName
of an asynchronous task in Loguru logs, follow these steps:
Import Necessary Modules:
Ensure you have the necessary imports, including asyncio
to access the current task and loguru
for logging.
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.
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())
taskName
feature in the logging module.💡 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!
as of Python 3.12, [logging module supports taskName](
If Anyone know how to display
taskName
in loguru format? Thanks a lot. )