Mayil-AI / loguru

MIT License
0 stars 0 forks source link

Log warning with their filename and line number (hashtag1092) #2

Open vikramsubramanian opened 3 months ago

vikramsubramanian commented 3 months ago

Hello, the [code snippets in loguru's doc]( show how to log warnings.

However, the snippet does not include the additional args of showwarning that are filename and lineno. I found no way of editing the log record to manually replace its file and line attribute.

Has anyone have an idea how to do such a thing without relying on extras? This would avoid me writing another formatter just to handle warnings )

mayil-ai[bot] commented 3 months ago

To log warnings with their filename and line number in Loguru without relying on extras, you can use the built-in warnings module to capture warnings and then log them using Loguru's logger. Here's a high-level overview of how you can achieve this:

Here's a code snippet that demonstrates how to do this:

import warnings
from loguru import logger

# Save the original showwarning
original_showwarning = warnings.showwarning

def loguru_showwarning(message, category, filename, lineno, file=None, line=None):
    # Log the warning using Loguru, including the filename and line number
    logger.warning(f"{filename}:{lineno}: {category.__name__}: {message}")
    # You can still call the original showwarning method if you want to
    # original_showwarning(message, category, filename, lineno, file, line)

# Override the showwarning
warnings.showwarning = loguru_showwarning

# Example usage
warnings.warn("This is a warning message")

This code snippet will log the warning message along with its filename and line number using Loguru's logger.warning method. The original showwarning method is saved so that you can still call it if you want to output the warning to the original location as well.