Open vikramsubramanian opened 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:
warnings
module.warnings.showwarning
to capture warnings.showwarning
method with a custom one that logs the warning using Loguru's logger, including the filename and line number.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.
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 arefilename
andlineno
. I found no way of editing the log record to manually replace itsfile
andline
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 )